读取C文件,读取一个额外的行,为什么呢? [英] Reading a C file, read an extra line, why?

查看:119
本文介绍了读取C文件,读取一个额外的行,为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么一个文件指针读取一个文件一个额外的行,特别是最后一行,这里是code:

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);  
}

和该文件具有恰好20行,但行20中,被打印的两倍。

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

这是错误?

先谢谢了。

推荐答案

您已经做了后两个读上二十行,你已经到了文件的的结束,但的系统没有按'知道这一点。当你试图让过去的文件末尾的feof只会触发,当你不完全就可以了...

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 ...

此外,您还可能对20日线的线端(CR或CR-LF),这只会让过去与另一个未遂阅读。

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.

解决方案是读取线一气呵成(有一个特定的C命令这一点),然后解析,让您的数据。如果整个线读取失败,那么你已经到了尽头。

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.

这篇关于读取C文件,读取一个额外的行,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆