#### Archived

This topic is now archived and is closed to further replies.

# Reading binary directly into a struct?

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

## Recommended Posts

I am a bit perplexed by reading straight binary from a file. I know it is possible to transfer a block of binary from a file directly into a data structure, but I''m having a bit of trouble doing it. I''m using an fstream with ios::in and ios::binary, and when I try to cout the variables I just get big integers. Also if this makes a difference I''m using a .dat that I had typed some text in just to test it out. Here''s my code so far:

WORD  wWidth;
WORD  wHeight;
DWORD dwExtra;
};

class CMyFile{

private:
fstream    INFILE;

public:
CMyFile(){}
~CMyFile(){}

bool OpenInfile(char* filename);
bool CloseInfile();
};

bool CMyFile::OpenInfile(char* filename){
//open file

INFILE.open(filename,ios::in|ios::binary);
if(!INFILE){ return false; }
else{ return true; }
}

//check output

//irrelevant stuff down here

}

The only reason I casted the cmfFileHeader to a pointer to char was because that''s the only way it would compile. I would suspect that''s causing problems but I''m not totally sure. Any help on this is greatly appreciated. Many thanks in advance, ~ MajorShredd ~

##### Share on other sites
with my limited c++ experience, it looks fine to me. are you sure your data in the file is ok? try viewing it in a hex editor. the cast is not a problem - the read funtion just needs an address, and casting it won''t change the address.

andy.

##### Share on other sites
quote:
Also if this makes a difference I''m using a .dat that I had typed some text in just to test it out.

Yes, that makes quite a big difference. The text you type in a text editor is merely ASCII representation of data. The actually binary value of what you type is different. Take a look at an ASCII chart to see the actual values for representable characters you type. Then you can get some data into the file simply by associating the binary data you want with the character you need to use. Otherwise, use a hex editor

And yes, casting it do a char is just fine. The function takes a pointer to a single-byte type so it can work in terms of bytes, and not any larger data type.

• ### Forum Statistics

• Total Topics
628668
• Total Posts
2984144

• 13
• 10
• 10
• 9
• 9