Search code examples
cloopsfeof

Extra Loop with EOF


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.


Solution

  • 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.