在 C 中使用 fgets 读取文本文件直到 EOF

Reading text-file until EOF using fgets in C

在 C 中使用 fgets 读取文本文件直到 EOF 的正确方法是什么?现在我有这个(简化):

char line[100 + 1];
while (fgets(line, sizeof(line), tsin) != NULL) { // tsin is FILE* input
   ... //doing stuff with line
}

具体来说,我想知道是否应该有其他东西作为 while-condition?从文本文件到 "line" 的解析是否必须在 while-condition 中执行?

根据 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).

所以检查返回值是否是NULL就够了。解析也进入 while-body。

你所做的是 100% OK,但你也可以简单地依靠 fgets 的 return 作为测试本身,例如

char line[100 + 1] = "";  /* initialize all to 0 ('[=10=]') */

while (fgets(line, sizeof(line), tsin)) { /* tsin is FILE* input */
    /* ... doing stuff with line */
}

为什么? fgets 将 return 指向 line 成功的指针,或 NULL 失败的指针(无论出于何种原因)。一个有效的指针将测试 true,当然,NULL 将测试 false.

(注意: 你必须确保 line 是一个 字符数组 声明在 范围内 使用 sizeof line 作为长度。如果 line 只是一个指向数组的指针,那么你只读取 sizeof (char *) 个字符)


我有同样的问题,我是这样解决的

while (fgets(line, sizeof(line), tsin) != 0) { //get an int value
   ... //doing stuff with line
}