Frage

I have a problem using the function feof, this is my code:

while(!feof(archlog))
{  if(!fgets(line,MAXLINE,archlog))
     printf("\nERROR: Can't read on: %s\n", ARCHTXT);
   else
     printf("%s",line);
}

When I run this, it prints the text of the file but makes an extra loop and prints the ERROR, I want to avoid this, I want it to only print the text of the file without the extra loop.

War es hilfreich?

Lösung 3

I always reverse the two function calls:

while(fgets(line,MAXLINE,archlog))
{  if(feof(archlog))
     break;
   else
     printf("%s",line);
}

That gets me out when the end of file is read. Sometimes I 'or' in ferror(archlog) to the feof() call, to break out on error or EOF.

Andere Tipps

The loop will enter once more if the file ends with a new line.

A warkaround whould be:

while(!feof(archlog))
{  if(!fgets(line,MAXLINE,archlog))
     printf("\nERROR: Can't read on: %s\n", ARCHTXT);
   else
     printf("%s",line);

   if ( (c=fgetc(archlog)) == EOF)
      break;
   ungetc(c, archlog);
}

The EOF flag is set once your gets function reads the EOF. This means that the last iteration will always trigger the error message. After this, the loop tests for the EOF flag again, which was triggered on the last read and thus exits the loop.

You could get around this by placing the EOF test inside the loop. There you can either print the text on a successful read or set a boolean to exit the loop if there is a failure.

You should not use feof(FILE *f) in your loops as it returns true only if EOF is read, not reached, see How to use feof(FILE *f)?

Instead use fgets and its return code for the condition:

while(fgets(line, MAXLINE, archlog) != NULL) {
    printf("%s", line);
}

There is no need for checking feof(archlog) inside the loop. For error checking use ferror(archlog).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top