Having trouble understanding a program(below).
I am little bit confused about the statement fputs("\n",fp)
eg. let me type:
It doesn't matter what you are underneath
Its what you do that defines you.
If I don't mention fputs("\n",fp)
the string appears in a single line. But with the code it is saved as typed.
Now the question is how the \n
is inserted in the desired place, cause' normally the \n
should be appended in the end of the text.
Any help would be seriously appreciated.
int main(){FILE *fp;char s[80];fp=fopen("abc.txt","w");if(fp==NULL){ puts("Cannot open file");exit(1);}printf("\nEnter a few lines of text:\n");while(strlen(gets(s))>0){fputs(s,fp);fputs("\n",fp);}fclose(fp);return 0;}
Best Answer
gets
(which shall not be used and has actually been removed from the most recent C standards) does not save the \n
in its buffer (while fgets
does).
And fputs
, unlike puts
, does not automatically insert one at the end of the string it writes. So by adding a fputs("\n", fp);
(or fputc('\n', fp)
) after outputting each typed line, you insert the missing newline in the file.
fputs
does not automatically add a newline to the output (in contrast with puts
which does).