Writing NULL char to file in C

Super Hacker picture Super Hacker · Apr 23, 2015 · Viewed 11k times · Source

I am attempting to write an array of char to a BMP file in C. The problem with this is that whilst 0x00 values are required for the file, it seems C interprets this as the end of string when writing to the file i.e. as a NULL char. Is there any way I can override this and have C rely purely on what I say is the number of char I wish to pass?

Code for writing the header to file (this function is executed in 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);
}

Answer

unwind picture unwind · Apr 23, 2015

Don't use fprintf() to write binary data, of course it's going to interpret its formatting string as a string. That's what it does!

Use fwrite(), and open your file in binary mode with "wb".

You can use sizeof to compute the size of the array, no need to hardcode the value:

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

This works because it's in the same scope as the array declaration of bmp1.