Home c Error reading file when using feof (C) function

Error reading file when using feof (C) function

Author

Date

Category

Wrote a program that counts the number of lines in a text file.

It calculates the lines correctly, but after I added a check for a file read error, the program for some reason displays an error message 47 times, and then still displays the correct result (by the way, there are only 25 characters in the file (not counting any control characters like \ n) and 21 lines). What’s the problem?

# include & lt; stdio.h & gt;
int main () {
  FILE * file;
  file = fopen ("C: /c/fff.txt", "r");
  if (file == NULL) {
    puts ("Error opening file.");
  }
  int lines = 1;
  while (! feof (file)) {// loop counting the number of lines in the file
    if (feof (file) == 0) {// check for file reading error
      puts ("Error reading.");
    }
    if (fgetc (file) == '\ n') {
      lines ++;
    }
  }
  printf ("% i", lines);
  fclose (file);
  return 0;
}

 enter image description here


Answer 1

The feof function checks if the end of the file has been reached. Returns 0 if not is reached and not zero otherwise.

Which means that the line if (feof (file) == 0) inside while (! feof (file)) is absolutely meaningless. If you go inside while , then the end of the file has not yet been reached.


Answer 2

As I understand it, the correct check for a file read error should look like this.

int c;
while (! feof (file)) {// loop counting the number of lines in the file
  c = fgetc (file);
  if (c == '\ n') {
    lines ++;
  }
}
if (c == EOF & amp; & amp; feof (file) == 0) {// check for file reading error
  puts ("Error reading");
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions