Extra Loop with EOF [duplicate]

╄→гoц情女王★ 提交于 2019-12-25 00:29:08

问题


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.


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/15368229/extra-loop-with-eof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!