将NULL char写入C中的文件

Sup*_*ker 1 c string hex file nul

我正在尝试将一个char数组写入C中的BMP文件.这个问题是,虽然文件需要0x00值,但是当写入文件时,似乎C将其解释为字符串的结尾,即为NULL焦炭.有什么方法可以覆盖这个并让C完全依赖于我说的是我希望通过的char数量?

将头写入文件的代码(该函数在main中执行);

void writeFile(void){
    unsigned char bmp1[54] = {
    0x42, 0x4D, 0x36, 0x00, 
    0x0C, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x36, 0x00, 
    0x00, 0x00, 0x28, 0x00, 
    0x00, 0x00, 0x00, 0x02, 
    0x00, 0x00, 0x00, 0x02, 
    0x00, 0x00, 0x01, 0x00, 
    0x18, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 
    0x0C, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00
    };

    FILE *picFile = fopen("pic.bmp","w");
    fprintf(picFile, bmp1, 54);
    fclose(picFile);
}
Run Code Online (Sandbox Code Playgroud)

unw*_*ind 6

不要fprintf()用来写二进制数据,当然它会将其格式化字符串解释为字符串.这就是它的作用!

使用fwrite(),并以二进制模式打开您的文件"wb".

您可以使用sizeof计算数组的大小,无需对值进行硬编码:

FILE *picFile = fopen("pic.bmp", "wb");
if(picFile != NULL)
  fwrite(bmp1, sizeof bmp1, 1, picFile);
fclose(picFile);
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为它与数组声明的范围相同bmp1.