fread 和 fwrite 扭曲文件二进制

fread and fwrite distort file binary

我正在尝试编写一个程序来创建设定大小的 .bmp。为此,我试图在每个文件的开头放置一组 header 。但是,每当我这样做时,字节似乎都会失真。而不是这个:

00000000  42 4d 7e c0 02 00 00 00  00 00 7e 00 00 00 6c 00  |BM~.......~...l.|
00000010  00 00 80 05 00 00 00 04  00 00 01 00 01 00 00 00  |................|
00000020  00 00 00 c0 02 00 13 0b  00 00 13 0b 00 00 01 00  |................|
00000030  00 00 01 00 00 00 42 47  52 73 00 00 00 00 00 00  |......BGRs......|
00000040  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
*
00000060  00 00 00 00 00 00 00 00  00 00 02 00 00 00 00 00  |................|
00000070  00 00 00 00 00 00 00 00  00 00 ff ff ff 00        |..............|
0000007e

我收到这个:

00000000  46 1d b3 1b 00 00 00 00  16 72 fd 55 00 00 00 00  |F........r.U....|
00000010  21 00 16 35 00 00 00 00  16 72 fd 55 00 00 00 00  |!..5.....r.U....|
00000020  21 00 16 35 00 00 00 00  00 00 00 00 00 00 00 00  |!..5............|
00000030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000040  40 52 69 01 00 00 00 00  a0 f7 f4 c4 fe 7f 00 00  |@Ri.............|
00000050  fa 0a 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000060  fa 0a 00 00 00 00 00 00  e9 67 a5 ad d8 7f 00 00  |.........g......|
00000070  40 f7 f4 c4 fe 7f 00 00  2e 07 40 00 00 00        |@.........@...|
0000007e

这是我正在使用的代码:

void basecopy() {              
  FILE *base, *test;

  base = fopen("base.bmp", "r");  //.bmp template
  test = fopen("test.bmp", "w");  //file to be copied to

  fseek(base, 0, SEEK_END);
  int size = ftell(base);
  fseek(base, 0, SEEK_SET);

  char buf[size];

  fwrite(buf, sizeof(char), size, test);
}

这是怎么回事?

您的代码从不调用 fread 来读取输入数据。因此,你在写垃圾。