bitmap fread behavior

Hello, I'm afraid this might be a bit of a noobie question,
but I'm coming across weird behavior when I use fread:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<stdio.h>

struct BITMAPFILEHEADER{
	char bfType[2];
	int bfSize;
	short bfReserved1;
	short bfReserved2;
	int bfOffBits;
} bmfh;

int main(){
	FILE * my_file = fopen("sample.bmp", "rb");
	
	fread(&bmfh, sizeof(struct BITMAPFILEHEADER), 1, my_file);
	printf("bfType = %c%c\n", bmfh.bfType[0], bmfh.bfType[1]);
	printf("bfSize (dec) = %d\n", bmfh.bfSize);
	printf("bfSize (hex) = %X\n", bmfh.bfSize);
	printf("bfReserved1 = %X\n", bmfh.bfReserved1);
	printf("bfReserved2 = %X\n", bmfh.bfReserved2);
	printf("bfOffBits (dec) = %d\n", bmfh.bfOffBits);
	printf("bfOffBits (hex) = %X\n", bmfh.bfOffBits);
	return 0;
}

I have the following output:

bfType = BM
bfSize (dec) = 36
bfSize (hex) = 24
bfReserved1 = 0
bfReserved2 = 36
bfOffBits (dec) = 2621440
bfOffBits (hex) = 280000


Whereas if I use it this way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<stdio.h>

struct BFTYPE{
	char magic[2];
} bfType;

struct BITMAPFILEHEADER{
	int bfSize;
	short bfReserved1;
	short bfReserved2;
	int bfOffBits;
} bmfh;

int main(){
	FILE * my_file = fopen("sample.bmp", "rb");
	
	fread(&bfType, sizeof(struct BFTYPE), 1, my_file);
	fread(&bmfh, sizeof(struct BITMAPFILEHEADER), 1, my_file);
	printf("bfType = %c%c\n", bfType.magic[0], bfType.magic[1]);
	printf("bfSize (dec) = %d\n", bmfh.bfSize);
	printf("bfSize (hex) = %X\n", bmfh.bfSize);
	printf("bfReserved1 = %X\n", bmfh.bfReserved1);
	printf("bfReserved2 = %X\n", bmfh.bfReserved2);
	printf("bfOffBits (dec) = %d\n", bmfh.bfOffBits);
	printf("bfOffBits (hex) = %X\n", bmfh.bfOffBits);
	return 0;
}

I get the following output:

bfType = BM
bfSize (dec) = 2359350
bfSize (hex) = 240036
bfReserved1 = 0
bfReserved2 = 0
bfOffBits (dec) = 54
bfOffBits (hex) = 36


Why is the output different?
It looks like the second way produces the result I want, but why don't they produce the same results?

In case it is relevant, I'm using gcc 4.6.1.
Memory alignment. You have two padding bytes between bfType und bfSize.
Best to read the values one by one. Or read the whole header into a char array (assuming you're using C) and extract the values from memory.
Topic archived. No new replies allowed.