【问题标题】:why is fscanf() never returning EOF?为什么 fscanf() 从不返回 EOF?
【发布时间】:2014-06-08 13:59:32
【问题描述】:

在下面的 sn-p 中,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

【问题讨论】:

    标签: c++ scanf stdio


    【解决方案1】:

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

    # this would be the comment line
    

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

    【讨论】:

    • 是的,我假设*scanf() 会跳过它不理解的行(例如以# 开头的行)。简单修复:使用while (getline(...) != EOF) 一次抓取一条线,使用sscanf()。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多