thruun
thruun

Reputation: 501

C fwrite() -ing an struct does not match fwrite() -ing the structs items separately

Good morning,

I am trying to write the content of following struct to a file (more specifically a BMP file) and am wondering why the binary outputs of fwriteing the entire struct and fwriteing the items of the struct separately differ. Is this the way C works? :O

typedef struct _BitmapFileHeader_
{
  u_int16_t bfType; // ID field - BM is the (Microsoft) standard, value should
                    // be 0x424D
  u_int32_t bfSize; // The size of the BMP file in bytes
  u_int32_t bfReserved; // Reserved, should be 0x0
  u_int32_t bfOffBits; // Offset of the byte where the image data begins
} BitmapFileHeader;

BitmapFileHeader bfh;

bfh.bfType = 0x4D42;
bfh.bfSize = (54 + 8);
bfh.bfReserved = 0;
bfh.bfOffBits = 54;

After using

fwrite(&bfh, sizeof(BitmapFileHeader), 1, img_handle)

the output of od -x output.bmp is:

4d42 0000 004e 0000 0000 0000 0036 0000

But when I use

fwrite(&bfh.bfType, sizeof(u_int16_t), 1, img_handle);
fwrite(&bfh.bfSize, sizeof(u_int32_t), 1, img_handle);
fwrite(&bfh.bfReserved, sizeof(u_int32_t), 1, img_handle);
fwrite(&bfh.bfOffBits, sizeof(u_int32_t), 1, img_handle);

the output is

4d42 004e 0000 0000 0000 0036 0000

Basically, fwrite seems to convert my u_int16_t to u_int32_t. Is this just regular behaviour of fwrite I should expect anyway, or am I missing some important point?

Cheers,

Upvotes: 0

Views: 102

Answers (1)

Pranit Kothari
Pranit Kothari

Reputation: 9859

Compiler adds padding to struct in order to align data in memory for performance. Size of struct will not always be adding size of its all members.

Add #pragma pack (1) at beginning of your file, and see the result. #pragma pack (1) will instruct compiler padding as 1 byte.

Upvotes: 1

Related Questions