fputs() newline behaviour in 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;
}

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'); after outputting each typed line, you insert the missing newline in the file.


Need Your Help

T4. Error: An expression block evaluated as Null

c# .net code-generation t4

I've added template.tt file that looks like:

Retrieve saved image from app and email

iphone ios4 iphone-sdk-3.0

I am succesfully saving an image to my app after the user takes a picture. What I want to do later is, when the user comes back to the app I want them to be able to email the photo as an attachment...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.