C读取二进制文件

标签 c file binaryfiles

<分区>

Possible Duplicate:
“while( !feof( file ) )” is always wrong

如果我将一个数组写入输出文件并关闭文件,然后再次打开文件并读取所有内容直到到达文件末尾,尽管文件只包含 4 个数字,程序将读取并打印 5数字,为什么?

程序输出:

a[0] = 4
a[1] = 7
a[2] = 12
a[3] = 34
a[4] = 34

save.bin(带十六进制编辑器)

04000000 07000000 0C000000 22000000

#include <stdio.h>
#include <stdlib.h>
#define path "save.bin"

int main(void)
{
  FILE *f=NULL;
  int a[]={4,7,12,34},i,n=4,k;
  f=fopen(path,"wb");
  if(f==NULL)
  {
    perror("Error");
    exit(1);
  }
  for(i=0;i<n;i++)  // or I could use fwrite(a,sizeof(int),n,f);
    fwrite(&a[i],sizeof(int),1,f);
  fclose(f);
  f=fopen(path,"rb");
  if(f==NULL)
  {
    perror("Error");
    exit(1);
  }
  i=0;
  while(!feof(f))
  {
    fread(&k,sizeof(int),1,f);
    printf("a[%d] = %d\n",i,k);
    i++;
  }
  printf("\n");
  fclose(f);
  return 0;
}

最佳答案

feof(fp) 仅当您尝试读取过去 文件末尾时才会变为 false(即非零值)。这应该可以解释为什么进入循环比您预期的多一个。

来自documentation :

  The function feof() tests the end-of-file indicator for the stream
  pointed to by stream, returning nonzero if it is set.  The end-of-
  file indicator can be cleared only by the function clearerr().

另请阅读帖子:Why is “while ( !feof (file) )” always wrong?

关于C读取二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12094966/

相关文章:

c - 为什么scanf总是返回1?

java - 未报告的异常 java.io.FileNotFoundException;?

c++ - std::ostream::write 有什么限制吗?

c - 如何从二进制文件读取到字符串/数组和 c 中的 int?

python - 只读取大文本文件的结尾

git 扩展和 *.xls

c - 为什么 BSS 中静态数组的第二个循环比第一个更快?

c - 通过地址获取函数名

c - 初始化 C 结构数组,其大小在编译时未知

c - 用 C 读取文本文件,将行分成多个变量