C读二进制文件

Cri*_*sti 7 c binaryfiles file

可能重复:
"while(!feof(file))"总是错误的

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

节目输出:

a[0] = 4
a[1] = 7
a[2] = 12
a[3] = 34
a[4] = 34
Run Code Online (Sandbox Code Playgroud)

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

04000000 07000000 0C000000 22000000
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 9

feof(fp)只有当您尝试读取文件末尾时才会变为假(即非零值).这应该可以解释为什么循环输入比你预期的多一个.

文档:

  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().
Run Code Online (Sandbox Code Playgroud)

另请阅读帖子:为什么"while(!feof(file))"总是错的?

  • +1用于解释如何设置`feof()`. (3认同)