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

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

提交回复
热议问题