c++ - 为什么 fscanf() 从不返回 EOF?

标签 c++ scanf stdio

在下面的代码片段中,fscanf() 总是返回 0,而不是 -1 (EOF)。结果,while 循环永远不会退出。知道为什么吗?

while ((n_items_read = fscanf(ifd, "%la, %la, %la\n", &x, &y, &z)) != EOF) {
  ...
}

完整代码如下:

void parse_test_file(const char* filename) {
  double x, y, z;
  int n_items_read, n_lines_read;

  FILE* ifd = fopen(filename, "r");
  if (NULL == ifd) {
    fprintf(stderr, "Failed to open %s for reading.\n", filename);
    return;
  }
  n_lines_read = 0;
  while ((n_items_read = fscanf(ifd, "%la, %la, %la\n", &x, &y, &z)) != EOF) {
    if (n_items_read != 3) {
      fprintf(stderr, "n_items_read = %d, skipping line %d\n", n_items_read, n_lines_read);
    }
    n_lines_read += 1;
  }
  fprintf(stderr, "Read %d lines from %s.\n", n_lines_read, filename);
  fclose(ifd);
}

...相关文件如下所示。 ((FWIW,我尝试编写和阅读更熟悉的 %lf 格式,但这并没有什么不同。)

# this would be the comment line
0x1.069c00020d38p-17, 0x1.0d63af121ac76p-3, 0x1.82deb36705bd6p-1
0x1.d5a86153ab50cp-2, 0x1.10c6de0a218dcp-1, 0x1.c06dac8380db6p-3
0x1.8163b60302c77p-5, 0x1.5b9427fab7285p-1, 0x1.5bccbd0eb7998p-1

最佳答案

问题出在输入文件的第一行。 *scanf() 不理解 shell 风格的注释。它只是输入文件中的另一行:

# this would be the comment line

*scanf() 系列函数由于格式不匹配而失败时,文件指针不会移过它。更好的办法是逐行读取然后解析它。

关于c++ - 为什么 fscanf() 从不返回 EOF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24106868/

相关文章:

c++ - Clang 访问修饰符顺序和 decltype

c++ - 为什么 11==011 返回 false?

c - 如何通过 Windows 批处理文件将值传递给 scanf()

使用 fscanf 时,我可以将非字母字符设置为 c 中的定界符吗?

c - AVR ATmega 在主循环之前使用 printf 时不断重置

c++ - C stdlib/stdio 的阴影函数

c++ - 简单链表C++函数调用后指针自动改变

c++ - 指针变量本身的内存位置?

c - C中从文件中读取字符串输入

c - 循环语句问题