Skip to main content
gamedev.net
🔒 Locked

Problem reading bitmap file

Started by w166um Apr 13, 2006 at 2:13 PM 3 replies 600+ views
Original Post
w166um
w166um
So i'm trying to read a bitmap file in my code...

typedef unsigned short Word;
typedef unsigned long  DWord ;

typedef struct {
	Word bfType;
	DWord bfSize;
	Word bfReserved1;
	Word bfReserved2;
	DWord bfOffBits;
} BITMAPFILEHEADER;


BITMAPFILEHEADER bmfh;
FILE* pFile;

pFile = fopen( "bitmap.bmp", "rb" );
fread( &bmfh, sizeof(BITMAPFILEHEADER), 1, pFile );

However the struct does not get the proper data. The file is a valid bitmap. Any suggestions? Thanks in advance.
Simian Man
Simian Man
Well your code looks OK to me, here's some stuff to try


  1. Check that fopen does not return NULL

  2. Open the file with a hex editor to see if it's what you think it should be

  3. Try reading the struct field by field to see where it goes wrong

w166um
w166um
fopen does not return null. Also the weird thing is if i read each member of the struct individually from the file I get the right values. However when i try the whole struct I get bad values. Seems to be some sort of alignment issue.
Evil Steve
Evil Steve
Your compiler is aligning the members of the structure to 4 bytes probably. That means that there's a spare 2 bytes after bfType, and probably after bfReserved1 and bfReserved2 too.

As the AP said - you should really use the version in windows.h (Or whatever file included from that).
If you're using Visual Studio, you can pack the structure like so:
#pragma pack(1)typedef struct {	Word bfType;	DWord bfSize;	Word bfReserved1;	Word bfReserved2;	DWord bfOffBits;} BITMAPFILEHEADER;#pragma pack()

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.