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;
}
fputs (buffer, output_file); writes the characters in buffer until a NULL is found. The NULL character is not written to the output_file. NOTE: fgets does not store the newline into the buffer, fputs will append a newline to the line written to the output file.
Return Value The fputs() function returns EOF if an error occurs; otherwise, it returns a non-negative value. The fputs() function is not supported for files that are opened with type=record.
fputs simply writes the string you supply it to the indicated output stream. fputs() doesn't have to parse the input string to figure out that all you want to do is print a string. fprintf() allows you to format at the time of outputting.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With