关于feof()导致文件最后一行重复读写的现象
今天在看网课学习c时,跟着老师的视频写了一个用fopen打开文件进行读写的操作,发现读文件最后一行总是重复。
话不多说,先贴代码:
#include<stdio.h>
int main()
{
FILE *fp;
double x,y;
fp=fopen("C:\\Users\\Administrator\\Desktop\\test.txt","r");
while(!feof(fp)){
fscanf(fp,"%lf %lf",&x,&y);
printf("%.3lf\t%.3lf\n",x,y);
}
fclose(fp);
return 0;
}
结果:
我的文件如下:
可见最后一行会重复打印。
网上看了一些老哥的贴,链接如下:
http://bbs.chinaunix.net/thread-956786-1-1.html
以及
https://stackoverflow.com/questions/14615671/whats-the-real-reason-to-not-use-the-eof-bit-as-our-stream-extraction-condition
截取有用信息:
这是对于fgets的情况,而对于fscanf的情况,稍作修改如下:
#include<stdio.h>
int main()
{
FILE *fp;
double x,y;
fp=fopen("C:\\Users\\Administrator\\Desktop\\test.txt","r");
while(!feof(fp)){
fscanf(fp,"%lf %lf",&x,&y);
if(feof(fp))break;
printf("%.3lf\t%.3lf\n",x,y);
}
fclose(fp);
return 0;
}
结果: