Jump to content
  • Advertisement
Sign in to follow this  
plywood

why read fails on binary files

This topic is 3930 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 am using fstream::read to read a binary file, but it doesn't seem to be working. Specifically I want to read two bytes from my data file.
int x;
fin.seekg(0, ios_base::beg);
fin.read((char*)x, 2);

cout << x;

I am trying to read the 1st two bytes of my file here. The code compiles, but I'm pretty positive that 2 things might be contributing to the reason for why 'x' never gets read: (1) read() only takes a char*, and so I might need to do some typecasting/dereferencing (2) it's a binary file (ios::in | ios::binary) What can I do to remedy this so that the binary values get read into my 'x' integer, and is there a simple way to do this? thanks guys

Share this post


Link to post
Share on other sites
Advertisement
You probably want something like:
fin.read(reinterpret_cast<char*>(&x), sizeof(int));
This is a pretty clunky way to do things though (there are other issues to consider as well, such as endianness, the size of the types involved, and so on).

If you're going to be doing a lot of this sort of thing, you might look into the Boost Serialization library.

Share this post


Link to post
Share on other sites
Quote:
Original post by jyk
You probably want something like:
fin.read(reinterpret_cast<char*>(&x), sizeof(int));
This is a pretty clunky way to do things though (there are other issues to consider as well, such as endianness, the size of the types involved, and so on).


To make this more clear for the original poster, the example I've quoted takes the address of 'x' and tells read() to put its output there, which is what you want. The original code takes the content of 'x' and tells read() to treat that as a pointer to where the output should go. It is quite likely to crash, and even if not, it definitely won't put anything actually into 'x'.

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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!