views:

78

answers:

1

Hi, I am trying to create a new bitmap file using C. This is a struct for the .bmp file header.

#define uint16 unsigned short
#define uint32 unsigned long
#define uint8  unsigned char
typedef struct 
{
 uint16 magic;  //specifies the file type "BM" 0x424d
 uint32 bfSize;  //specifies the size in bytes of the bitmap file
 uint16 bfReserved1;  //reserved; must be 0
 uint16 bfReserved2;  //reserved; must be 0
 uint32 bOffBits;  
} BITMAPFILEHEADER;

In my program I am doing this.

main() {
FILE* fp;
fp = fopen("test.bmp", "wb");
 BITMAPFILEHEADER bmfh;
 BITMAPINFOHEADER bmih;

 bmfh.magic = 0x4d42; // "BM" magic word
 bmfh.bfSize = 70; 
 bmfh.bfReserved1 = 0;  
 bmfh.bfReserved2 = 0; 
 bmfh.bOffBits = 54; 
fwrite(&bmfh, sizeof(BITMAPFILEHEADER), 1, fp);
fclose(fp);
}

So, when I read my test.bmp file it should contain 14 bytes (size of the stuct) and the values should be

42 4d 46 00 00 00 00 00 00 00 36 00 00 00

But if I read the file it shows me 16 bytes:

42 4d 04 08 46 00 00 00 00 00 00 00 36 00 00 00

From where does this "04 08" come.? My bmp file becomes corrupted.

My question is that in binary file I/O if I write a structure to a file and its size is not multiple of 4Bytes (32 bit), does it automatically change the structure?

Any idea how to get around with this?

+4  A: 

Your structure is being padded. The 04 08 is a garbage value from your stack. You need to use whatever feature your compiler provides to pack the structure. In most cases you should be able to use #pragma pack(1):

#pragma pack(1)  // ensure structure is packed
typedef struct 
{
   .
   .
   .
} BITMAPFILEHEADER;
#pragma pack(0)  // restore normal structure packing rules

You can read about data structure padding on wikipedia.

Carl Norum
Yup,That solved it. Thanks a lot.
Punit Soni