开发者

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?


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.


from man fgets

gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with '\0'. No check for buffer overrun is performed (see BUGS below).

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.

and thus fgets behaviour is different from what you might expect


From the linux man page for fgets():

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in thebuffer.


fgets() includes the newline when reading into the string - that's how fgets() is defined to work. From the standard:

No additional characters are read after a new-line character (which is retained) or after end-of-file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜