为什么fscanf()永远不会返回EOF?

时间:2014-06-08 13:59:33

标签: 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

1 个答案:

答案 0 :(得分:5)

问题是输入文件中的第一行。 *scanf()无法理解shell样式注释。它只是输入文件中的另一行:

# this would be the comment line

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