Search code examples
cfgets

Why is my output formatted, i.e. '\n' automatically in fgets?


Here is my code

#include<stdio.h>
int main()
{
FILE* fp;
int i;
fp=fopen("newfile","r");
if(fp==NULL)
{
   printf("hhaha");
   return 0;
}
char str[20];
for(i=0;i<2;i++)
{
    fgets(str,20,fp);
    printf("%s",str);
} 
return 0;
}

Now if my newfile has text

my name
is xyz

then how come when i print the two lines are printed in two newlines? where does the newline character come from?


Solution

  • fgets sets the pointer to a char * representing the line of the file including the \n at the end of the line. (As is the case with most strings, it will also be '\0' terminated)

    A file with this:

    This
    is
    my
    file

    Will have this from fgets:

    This\n\0,is\n\0,my\n\0,file\n\01


    1The final value may not be include \n. That will depend on whether it is a \n terminated file.