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
#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;
}
Comments
Leave a comment