I wanted to read input from user (multiple lines) and write it into a file using fputs().
Here is my code
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char s[25];
fp=fopen("myname","w");
if(fp==NULL)
{
perror("Error opening file\n");
exit(1);
}
while(fgets(s,25,stdin)!=NULL)
fputs(s,fp);
fclose(fp);
return 0;
}
After getting input from user, i am using Ctrl+C to close the input prompt of the program (I'm using linux). Then if i open the file, it contains nothing. How could I resolve this?
Is there anything wrong with the usage of fputs() & fgets()?
Since C-C
likely kills the process, because of buffering, the lines won't get to the file (unless there's a lot of them and they fill the buffer).
You should end the output with C-D
(Unix) or C-Z
(Dos), not C-C
.
As a side note: fgets
doesn't strip the newline and fputs
adds its own. But I guess you were going to notice that :-)