How to use feof(FILE *f)?

后端 未结 3 1830
野的像风
野的像风 2020-12-06 22:55

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]         


        
相关标签:
3条回答
  • 2020-12-06 23:38

    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.

    0 讨论(0)
  • 2020-12-06 23:44

    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.

    0 讨论(0)
  • 2020-12-06 23:56

    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
    
    0 讨论(0)
提交回复
热议问题