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

来源:互联网 发布:java获取磁盘io 编辑:程序博客网 时间:2024/05/21 07:09
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
原创粉丝点击