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

前端 未结 6 1884
余生分开走
余生分开走 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: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().

提交回复
热议问题