Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fputs() newline behaviour in c

Tags:

c

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;
}
like image 811
Broskiee Avatar asked Nov 20 '13 14:11

Broskiee


People also ask

Does Fputs print newline?

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.

What does Fputs return C?

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.

Why would you use Fputs?

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.


2 Answers

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.

like image 178
Medinoc Avatar answered Oct 12 '22 04:10

Medinoc


fputs does not automatically add a newline to the output (in contrast with puts which does).

like image 24
John Källén Avatar answered Oct 12 '22 04:10

John Källén