why is fscanf() never returning EOF?

fearless_fool

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

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

Full code follows:

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 the file in question looks like this. ((FWIW, I tried writing and reading the more familiar %lf format, but that didn't make a difference.)

# 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
P.P

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

# this would be the comment line

When *scanf() family functions fail due to the format mismatch, the file pointer doesn't move past it. Better idea would be to read line-by-line and then parse it.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related