Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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", "r") ;
int mac;
char *ip = (char *) malloc(15);

while(!feof(fp)){
    fscanf(fp,"%i",&mac);
    fscanf(fp,"%s",ip);

    printf("MAC: %i\n",mac);
    printf("IP: %s\n",ip);  
}

and the file has exactly 20 lines, but the line 20, is printed twice.

Which is the error?

Thanks in advance.

like image 438
Joe Lewis Avatar asked Dec 10 '22 01:12

Joe Lewis


2 Answers

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.

like image 124
svinja Avatar answered Dec 28 '22 03:12

svinja


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);  
}
like image 29
Sergey Kalinichenko Avatar answered Dec 28 '22 04:12

Sergey Kalinichenko