[英]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是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. fgets
将指针设置为char *
的指针,该char *
表示文件的行,在该行的末尾包含\\n
。 (As is the case with most strings, it will also be '\\0'
terminated) (与大多数字符串一样,它也将以
'\\0'
终止)
A file with this: 带有以下内容的文件:
This
这个
is是
my我的
file文件
Will have this from fgets
: 将来自
fgets
:
This\\n\\0
, is\\n\\0
, my\\n\\0
, file\\n\\0
1 This\\n\\0
, is\\n\\0
, my\\n\\0
, file\\n\\0
1
1 The final value may not be include \\n
. 1最终值不能包含
\\n
。 That will depend on whether it is a \\n
terminated file. 这将取决于它是否为
\\n
终止文件。
from man fgets
来自
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'.
gets()从stdin读取一行到s所指向的缓冲区,直到终止换行符或EOF,然后将其替换为'\\ 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.
fgets()最多从流中读取小于大小的字符,并将它们存储到s所指向的缓冲区中。 Reading stops after an EOF or a newline.
在EOF或换行符之后停止读取。 If a newline is read, it is stored into the buffer .
如果读取了换行符,则将其存储在buffer中 。 A '\\0' is stored after the last character in the buffer.
缓冲区的最后一个字符之后将存储一个'\\ 0'。
and thus fgets
behaviour is different from what you might expect 因此
fgets
行为与您预期的不同
From the linux man page for fgets(): 在Linux手册页中的fgets()中:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.
fgets()最多从流中读取小于大小的字符,并将它们存储到s所指向的缓冲区中。 Reading stops after an EOF or a newline.
在EOF或换行符之后停止读取。 If a newline is read, it is stored into the buffer.
如果读取换行符,则将其存储到缓冲区中。 A '\\0' is stored after the last character in thebuffer.
缓冲区中的最后一个字符之后将存储一个'\\ 0'。
fgets()
includes the newline when reading into the string - that's how fgets()
is defined to work. 当读取字符串时,
fgets()
包括换行符-这就是fgets()
定义为工作方式的方式。 From the standard: 从标准:
No additional characters are read after a new-line character (which is retained) or after end-of-file.
在换行符(保留)或文件结束之后,不会读取其他字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.