views:

54

answers:

2

I need to read exactly 32 bits from a file. I'm using ifstream in the STL. Can I just directly say:

int32 my_int;
std::ifstream my_stream;

my_stream.open("my_file.txt",std::ifstream::in);
if (my_stream && !my_stream.eof())
   my_stream >> my_int;

...or do I need to somehow override the >> operator to work with int32? I don't see the int32 listed here: http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/

+2  A: 

int32 will be a typedef for whatever type happens to be a 32-bit signed integer on your platform. That underlying type will certainly have operator>> overloaded for it.

Update

As Billy pointed out below, streams are designed to read text and parse it into the overloaded data type. So in your code example, it will be looking for a sequence of numeric characters. Therefore, it won't read 32 bits from your file.

Oli Charlesworth
But that won't read exactly 32 bits from the file.
Billy ONeal
@Billy: good point, I'll update my answer...
Oli Charlesworth
+1 for the edit.
Billy ONeal
+3  A: 

The stream extraction operator (>>) performs formatted IO, not binary IO. You'll need to use std::istream::read instead. You'll also need to open the file as binary. Oh, and checking std::istream::eof is redundant in your code.

int32 my_int;
std::ifstream my_stream;

my_stream.open("my_file.txt",std::ios::in | std::ios::binary);
if (my_stream)
{
    my_stream.read(reinterpret_cast<char*>(&my_int), sizeof(my_int));
}
//Be sure to check my_stream to see if the read succeeded.

Note that doing this is going to introduce platform dependence on your code, because the order of bytes in an integer is different on different platforms.

Billy ONeal
True, but isnt big endian pretty much dying or dead? I havent seen a solaris system in ages...
Jason R. Mick
@Jason: ARM isn't dying or dead :) Also, most file formats and network protocols are specified as big endian (for some reason).
Billy ONeal
oh yea forgot that ARM is big end endian. doh! Good thing my code won't be used on any smart phones though ;o)
Jason R. Mick
But ultimately, anytime you're dealing with a binary file that stores int data, you have to worry about endianness right? So isn't that a given?
Jason R. Mick
@Jason: Yes, but if you write the loading character by character, then you can read the same file on different platforms without issue. I.e. an ARM in big endian mode can write a file and an x86 will be able to read the same file. Doesn't really matter which one you pick, just so long as you pick one. You would need to write endian flipping code here if you wanted to port to another platform. Alternately you could store the number as **text** and forget about the whole issue.
Billy ONeal
Yea there's a flag for endian-ness in the file format I'm working with, I figured out. Granted the vast majority of applications will be big endian as there's not much chemical simulations software on cell phones (yet!).
Jason R. Mick