C语言 fgets 在文件中逐行读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21180248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fgets to read line by line in files
提问by codeara
I understand that fgets reads until EOF or a newline.
我知道 fgets 读取直到 EOF 或换行符。
I wrote a sample code to read lines from a file and I observed that the fgets gets executed more than the desired number of times. It is a very simple file with exactly two blank lines, ie. I pressed enter once and saved the file.
我编写了一个示例代码来从文件中读取行,我观察到 fgets 的执行次数超过了所需的次数。这是一个非常简单的文件,只有两个空行,即。我按了一次 Enter 并保存了文件。
Below is the code:
下面是代码:
fp = fopen("sample.txt","r");
while (!feof(fp)) {
fgets(line,150,fp);
i++;
printf("%s",line);
}
printf("%d",i);
Why is the while loop getting executed three times instead of 2, as there are only two blank lines in the file?
为什么 while 循环执行 3 次而不是 2 次,因为文件中只有两个空行?
回答by M Oehm
In your case, the last line is seemingly read twice, except that it isn't. The last call to fgetsreturns NULLto indicate the the end of file has been read. You don't check that, and print the old contents of the buffer again, because the buffer wasn't updated.
在您的情况下,最后一行似乎被读取了两次,但事实并非如此。最后一次调用fgets返回NULL指示已读取文件末尾。你不检查,再次打印缓冲区的旧内容,因为缓冲区没有更新。
It is usually better not to use feofat all and check return values from the f...family of functions:
通常最好不要使用feof并检查f...函数系列的返回值:
fp = fopen("sample.txt", "r");
while (1) {
if (fgets(line,150, fp) == NULL) break;
i++;
printf("%3d: %s", i, line);
}
printf("%d\n",i);
The function feofreturns true after trying to read beyondthe end of the file, which only happens after your last (unsuccessful) call to fgets, which tries to read ator rather just before the end of the file. The answers in this long SO postexplain more.
该函数feof返回试图读取后真正超越文件,其中只有最后一次(不成功)调用后会结束fgets,尝试读取的或者说是文件结束前。这篇冗长的 SO 帖子中的答案解释了更多。

