How to use feof(FILE *f)?

那年仲夏 提交于 2019-12-17 16:53:39

问题


I'm having a hard time with a do-while loop, that is supposed to stop when we reach the end of the file. Here's the loop code:

do  {
    if (pcompanyRow[0] != '#' && pass == 1) {
        strtok(pcompanyRow, ":");
        pcompanyName = strcpy(pcompanyName, strtok(NULL, ""));
        pass = 2;
        fgets(pcompanyRow, 1024, f);
    }
    if (pcompanyRow[0] != '#' && pass == 2) {
        strtok(pcompanyRow, ":");
        pcompanySMSPrice = strcpy(pcompanySMSPrice, strtok(NULL , ""));
        pass = 3;
        fgets(pcompanyRow, 1024 , f);
    }
    if (pcompanyRow[0] != '#' && pass == 3) {
        strtok(pcompanyRow, ":");
        pcompanyMMSPrice = strcpy(pcompanyMMSPrice, strtok(NULL, ""));
        pass = 4;
        fgets(pcompanyRow, 1024, f);
    }
    if (pass == 4)  {
        AppendCompanyNode(pcompanyList, pcompanyName, pcompanySMSPrice, pcompanyMMSPrice);
        pass = 1;
    }
} while (!feof(f));

After running with the debugger, I noticed that all the crash problems I have are because it doesn't go out of this loop even when it reached the whole lines.

How should I write it correctly?


回答1:


I would change your loop and logic to use this:

while (fgets(pcompanyRow, 1024, f) != NULL) {

    /* do things */

}

when fgets() attempts to read past the end of the file, it will return NULL and you'll break out of the loop. You can still continue to use pass and your other flags/logic, but the conditions you check for will be slightly different.




回答2:


You should never use feof() as the exit indicator for a loop. feof() is TRUE only after the end of file (EOF) is read, not when EOF is reached

Source here. It also explains the problem in detail and how to fix it.




回答3:


I suggest use both fgets() and feof(). Last string in file might have \n or might not. If you use only feof(), you can skip (lost) last line.

 for(;;)
 {char *pc;

  pc=fgets(buf,sizeof(buf),fd);

  if(!pc)
    {//it may be read error or end of file
      if(feof(fd))
        {//it is end of file, normal exit from for
         break;      
        }
       else
        {//it is i/o error 
         fclose(fd);
         return 2;
        }
    }
}//for


来源:https://stackoverflow.com/questions/4299296/how-to-use-feoffile-f

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