如何区分到达 EOF 和到达错误的 fgets

how to differentiate between fgets reaching EOF and reaching error

我有一个关于 fgets()

的问题
char *fgets(char *str, int strsize, FILE *stream);

fgets()' 文档说:

On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned.

If an error occurs, a null pointer is returned.

  1. 你如何区分以上两种情况 - fgets 到达 EOF(文件结束)和读取文件时出错?

  2. 此外,当 fgets 读取文件时发生错误时,fgets 是否会跟踪 str 中到目前为止已读取的内容?

  3. 如何检查 fgets 是否立即到达 EOF?

提到你的第一个问题:

How do you differentiate between above two situations - fgets reaching EOF(END OF FILE) & error whilst reading file?

如果 fgets() 返回 NULL,则为文件指针调用 ferror(),该文件指针刚刚在 fgets() 调用中使用,返回 NULL。如果 ferror() returns 为非零值,则 fgets() 失败,否则它已到达文件末尾。

示例:

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

#define LINE_LEN_MAX (42)

int main(int argc, char ** argv)
{
   if (1 >= argc)
   {
     errno = EINVAL;
     perror("main() failed");
     exit(EXIT_FAILURE);
   }

   {
     FILE * fp = fopen(argv[1], "r");
     if (NULL == fp)
     {
       perror("fopen() failed");
       exit(EXIT_FAILURE);
     }

     for (char line[LINE_LEN_MAX];
       NULL != fgets(line, LINE_LEN_MAX, fp);)
     {
       printf("%s", line);
     }

     if (0 != ferror(fp))
     {
       perror("fgets() failed");
       exit(EXIT_FAILURE);
     }

     fclose(fp);
   }

   return EXIT_SUCCESS;
 }

另一个问题可以从 the docs:

直接回答

问题 3:

How do you check if fgets immediately reaches EOF?

答案:

If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned.

问题 2:

when an error occurs whilst fgets reads file, does fgets keep track of whatever has been read up to that point in the str?

答案:

If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned.