Jump to content
  • Advertisement
Sign in to follow this  

BMP, writing to a struct

This topic is 3302 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I ahve my struct
typedef struct _tBMP_HEADER
    unsigned short type;	// must be 19778
    unsigned long size;		// size of BMP file (in bytes)
    unsigned short reserved1;	// reserved, leave 0
    unsigned short reserved2;	// reserved, leave 0
    unsigned long imageOffset;	// offset to image data (in bytes)

Within the loading function I have
FILE *pFile;   // file pointer
errno_t error; // used by fopen_s

error = fopen_s(&pFile, filename, "rb");         // open the file as read binary

if (pFile == NULL || error != 0)                 // check it opened ok
    return BMP_RETURN_FAIL_OPENFILE;             // just end now if it didnt

fread(&m_header, sizeof(BMP_HEADER), 1, pFile);  // read the header and store it

However when debugging and looking at m_header its shown as:
type =        19778
size =        0
reserved1 =   0
reserved2 =   1078
imageOffset = 2621440

Any help appreciated ty :) [Edited by - jpetrie on September 11, 2009 10:26:30 AM]

Share this post

Link to post
Share on other sites
The problem is almost certainly that your compiler tries to align the structure's size field on a 32-bit boundary, thus adding two bytes of padding after the type word.

There are ways of forcing many compilers to omit this padding but they're not exactly portable, so if you are targeting Windows then you're probably better off including <windows.h> and making use of BITMAPFILEHEADER instead. And if that's not feasible then I suggest extracting the fields manually, that is without a structure, and dealing with byte order issues while you're about it.

Share this post

Link to post
Share on other sites
You're forgetting to take into account of struct padding. Either set the struct to have 1 byte alignment using

#pragma pack(1)

or read each member into the struct at a time.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!