Answer to Question #302042 in C for Suvedhaa

Question #302042

Implement a C program for file operations to read a string from standard input and prints the entered string using fgets() and fputs() function.

Note: Create the text file, fstring.txt

Input :

Hai

Output :

Hai


1
Expert's answer
2022-02-25T03:39:46-0500
#include <stdio.h>

int main()
{
    char message [256];
    char* filename = "D://fstring.txt";
    char ch[256];
    FILE *mfile;
    printf("Enter the string: ");
    scanf("%s", &message);
    // writing to file
    if((mfile = fopen(filename, "w"))==NULL)
    {
        perror("Error occured while opening file");
        return 1;
    }
    // write a string
    fputs(message, mfile);
    fclose(mfile);
     
    // reading from a file
    printf("Output:\n");
    if((mfile = fopen(filename, "r"))==NULL)
    {
        perror("Error occured while opening file");
        return 1;
    }
    //  read 256 bytes
    while((fgets(ch, 256, mfile))!=NULL)
    {
        printf("%s", ch);
    }
     
    fclose(mfile);
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS