Skip to main content
gamedev.net
🔒 Locked

fstream problem...

Started by Houdini Oct 9, 2000 at 10:00 AM 1 replies 850+ views
Original Post
Houdini
Houdini
I''m having a problem reading in a binary file using fstream. I can open the file fine, I can read values individually just fine, but I run into problems when I try to read in a section of the file into a structure. Here''s what I got:
WORD a;
DWORD b;

m_fstrFile.read((unsigned char*)&a, 2);
m_fstrFile.read((unsigned char*)&b, 4);

 
This reads in perfectly fine, giving the correct values for a and b (a = 19,778 and b = 342,198). But this doesn''t work:
struct mystruct
{
   WORD a;
   DWORD b;
};

mystruct c;

m_fstrFile.read((unsigned char*)&c, sizeof(mystruct));
 
Here a is correctly given the value of 19,778 but b is given the value of 5. Anyone have any clues why this isn''t working correctly? - Houdini
Houdini
MicahJon
MicahJon
My guess is that you don't have your structures set to Byte alignment. By default most compilers will align the members of a structure to 32bit boundaries. Any members that aren't 32 bits are padded to take up 32bits in the structure, which always causes problems when reading from a file (as your doing here).

Two solutions:

Overide operator >> and operator << for your structure, so that it reads the elements one at a time. Correct me if I'm wrong someone, but I think this is the most efficient during game time, as it preserves the 32bit byte alignment. It's might be slower during load time though.

Or you can set your byte alignment to 1. This is usually the easiest, and is done trough your compiler options or through a pragma (#pragma pack(1) in Borland)

Micah

Edited by - MicahJon on October 9, 2000 11:42:19 AM
Houdini
Houdini
Using #pragma pack(1) worked like a charm, thanks!
Houdini

Topic Locked

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

Sign in to reply to this topic.