Problem writing raster header file in C

I am trying to create a new bitmap file using C. This is the structure for the header of the .bmp file.

#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 do 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 the test.bmp file, it should contain 14 bytes (stuct size), 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 will display me 16 bytes:

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

Where does this “04 08” come from? My bmp file is corrupt.

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

Any idea how to get around this?

+3
1

. 04 08 - . , . #pragma pack(1):

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

.

+8

Source: https://habr.com/ru/post/1764078/


All Articles