Question

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/

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top