C语言 在 C 中使用 fgets 读取文本文件直到 EOF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38976582/
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
Reading text-file until EOF using fgets in C
提问by Johan
what is the correct way to read a text file until EOF using fgets in C? Now I have this (simplified):
在 C 中使用 fgets 在 EOF 之前读取文本文件的正确方法是什么?现在我有了这个(简化):
char line[100 + 1];
while (fgets(line, sizeof(line), tsin) != NULL) { // tsin is FILE* input
... //doing stuff with line
}
Specifically I'm wondering if there should be something else as the while-condition? Does the parsing from the text-file to "line" have to be carried out in the while-condition?
具体来说,我想知道是否应该有其他东西作为 while 条件?从文本文件到“行”的解析是否必须在 while 条件下进行?
回答by bigahega
According to the reference
根据参考
On success, the function returns str. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer(and the contents of str remain unchanged). If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
成功时,该函数返回 str。如果在尝试读取字符时遇到文件尾,则设置 eof 指示符 (feof)。如果在读取任何字符之前发生这种情况,则返回的指针是空指针(并且 str 的内容保持不变)。如果发生读取错误,则设置错误指示符(ferror)并返回空指针(但 str 指向的内容可能已更改)。
So checking the returned value whether it is NULLis enough. Also the parsing goes into the while-body.
所以检查返回值是否NULL足够。解析也进入while-body。
回答by David C. Rankin
What you have done is 100% OK, but you can also simply rely on the return of fgetsas the test itself, e.g.
你所做的是 100% OK,但你也可以简单地依赖于fgets作为测试本身的返回,例如
char line[100 + 1] = ""; /* initialize all to 0 ('while (fgets(line, sizeof(line), tsin) != 0) { //get an int value
... //doing stuff with line
}
') */
while (fgets(line, sizeof(line), tsin)) { /* tsin is FILE* input */
/* ... doing stuff with line */
}
Why? fgetswill return a pointer to lineon success, or NULLon failure (for whatever reason). A valid pointer will test trueand, of course, NULLwill test false.
为什么?fgets将返回一个指向line成功或NULL失败的指针(无论出于何种原因)。一个有效的指针将测试true,当然,NULL将测试false。
(note:you must insure that lineis a character arraydeclared in scopeto use sizeof lineas the length. If lineis simply a pointer to an array, then you are only reading sizeof (char *)characters)
(注意:您必须确保这line是在范围内声明的字符数组以用作长度。如果只是指向数组的指针,那么您只是在读取字符)sizeof linelinesizeof (char *)
回答by user3499663
i had the same problem and i solved it in this way
我有同样的问题,我以这种方式解决了

