Why fscanf () never returns EOF?

In the following snippet, fscanf () always returns 0, not -1 (EOF). As a result, the while loop never terminates. Any idea why?

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

Full code:

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);
}

... and this file looks like this. ((FWIW, I tried writing and reading the more familiar% lf format, but that didn't matter.)

# 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
+4
source share
1 answer

The problem is the first line of your input file. *scanf()doesn't understand shell-style comments. This is just another line in the input file:

# this would be the comment line

*scanf() - , . , .

+5

Source: https://habr.com/ru/post/1543755/


All Articles