为什么fread()在读取二进制文件后无法在缓冲区中存储二进制值?

时间:2017-11-30 09:52:54

标签: binaryfiles

我希望以下代码将输出结果如下:

a[0] = 0
a[1] = 1
b[0] = 2
b[1] = 3
b[2] = 4

但真正的结果是:

a[0] = 0
a[1] = 0
b[0] = 0
b[1] = 0
b[2] = 0

为什么呢?我认为[2]和b [3]中的原始值将被二进制文件覆盖,但事情的真相却完全不同了,谢谢。

#include <stdio.h>

int
main ()
{
  FILE *data;

  data = fopen ("binary.dat", "w+");

  unsigned char buffer[5];

  for (int i = 0; i <= 4; i++)
    {   
      buffer[i] = i;
    }   

  fwrite (buffer, sizeof (unsigned char), 10, data);

  int a[2] = {0};
  int b[3] = {0};

  fread (a, sizeof (int), 2, data);
  fread (b, sizeof (int), 3, data);

  for (int i = 0; i <= 1; i++)
    {   
      printf ("a[%d] = %d\n", i, a[i]);
    }   

  for (int i = 0; i <= 2; i++)
    {   
      printf ("b[%d] = %d\n", i, b[i]);
    }   

  fclose (data);

  return 0;
}    

0 个答案:

没有答案