C 库函数 feof(FILE*) 判断文件末尾的问题

本文探讨了使用C库函数feof判断文件末尾时出现的常见错误,并提供了一种正确的实现方式,避免了文件重复读取的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C 库函数 feof(FILE*) 判断文件末尾的问题A Problem on Using C Library Function feof(FILE*) to Judge The End of A File
我用 C 写了一个程序读取 32768 字节大小的文件,每次读 16 个字节,应该是 2048 次读完。但结果读了 2049 次,并且最后两次的数据相同,似乎重复读取了最后 16 个字节。源代码如下:    I wrote a program with C, which read a file of 32768 bytes, 16 bytes each time, and it should finish reading after 2048 times. But the reault was it read 2049 times, and the data of last two times are the same, which seemed the last 16 bytes were read twice. Here is the code:
  1. int loop = 0;
  2. while (!feof(file)) {
  3.     loop++;
  4.     fread(buffer, 16, 1, file);
  5.     ......
  6. }
  7. printf("%d\n", loop);    // 2049
我看了一阵,发现导致这个错误的原因是 feof(FILE*) 判断文件末尾的机制:文件指针在文件末尾的时候,除非再读一次导致发生 I/O 错误,feof(FILE*) 依然返回 0。因此用feof(FILE*) 作为判断条件的 while 循环始终会多读一次,而最后一次的读取是失败的,buffer 也就没有改变,看起来就像是重复读了一次。    I reviewed it for a whil and found the reason that produced this error is the mechanism feof(FILE*) used to judge the end of a file: When the file pointer is at the end of a file, feof(FILE*) still returns 0 unless reads one more time to course a I/O error. Therefore, a while loop using feof(FILE*) as the judgment condition always reads one more time, and the last time of reading will fail, so buffer stayed unchanged which looked like it repeated reading once.
用下面的代码就没问题了:    Use the code below to solve this problem:
  1. int loop = 0;
  2. while (fread(buffer, 16, 1, file) == 1) {
  3.     loop++;
  4.     ......
  5. }
  6. printf("%d\n", loop); // 2048
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值