Reading a C file, read an extra line, why?

前端 未结 6 1871
余生分开走
余生分开走 2020-12-21 05:12

I don\'t know exactly why a file pointer reads an extra line from a file, specifically the last line, here is the code:

FILE *fp ;
fp = fopen (\"mac_ip.txt\"         


        
相关标签:
6条回答
  • 2020-12-21 05:39

    feof does not "know" it's at the end of file until you try to read some more. Since fscanf tells you how many items it got, you can use this simple trick:

    for(;;){
        if (fscanf(fp,"%i%s", &mac, ip) != 2) break;
        printf("MAC: %i\n",mac);
        printf("IP: %s\n",ip);  
    }
    
    0 讨论(0)
  • 2020-12-21 05:42
    FILE *fp ;
    int mac;
    char ip[15];
    
    fp = fopen ("mac_ip.txt", "r") ;
    if (!fp) return;
    
    while(1){
        if (fscanf(fp,"%i",&mac) < 1) break;
        if (fscanf(fp,"%s",ip) < 1) break;
    
        printf("MAC: %i\n",mac);
        printf("IP: %s\n",ip);  
    }
    fclose (fp);
    

    fscanf() returns the number of assignments it mad (or -1 on eof). By using the return value, you don't need the eof() function. BTW I don't think you can read a MAC address into an int. Maybe you need to read that into a string, too ?

    Explanation: feof() does not do what the OP expects. feof() should only be inspected after one of the file operations failed. In most cases you don't need feof().

    0 讨论(0)
  • 2020-12-21 05:43

    Your code resembles to the following example

    #include <stdio.h>
    
    int main(void)
    {
        char buffer[256];
        FILE * myfile;
    
        myfile = fopen("some.txt","r");
    
        while (!feof(myfile))
        {
            fgets(buffer,256,myfile);
            printf("%s",buffer);
        }
    
        fclose(myfile);
    
        return 0;
    }
    

    from

    http://www.friedspace.com/feof.html

    0 讨论(0)
  • 2020-12-21 05:46

    After you have done the two reads on the twentieth line, you have got to the end of the file but the system doesn't know this. feof will only trigger when you try to get past the end of the file, not when you are exactly on it ...

    Also, you may have a line-end (CR or CR-LF) on the 20th line which it will only get past with another attempted read.

    The solution is to read the line in one go (there is a specific C command for this) and then parse that to get your data. If the whole-line read fails, then you've got to the end.

    0 讨论(0)
  • 2020-12-21 05:50

    Because after reading the last two values, you still haven't hit EOF. So the loop goes on. In the next pass of the loop, fscanf actually does not read the last line for the second time like it appears, the fscanfs fail, but the printfs print out the values from the previous pass of the loop.

    0 讨论(0)
  • 2020-12-21 05:53

    You better test for fscanf return value before printing result. I bet that in the last iteration of your loop, fscanf calls fail and you print the last returned results.

    0 讨论(0)
提交回复
热议问题