Discussion Locked

Binary File IO with ofstream

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Hi,
I'm trying to write binary data to an ofstream object and I'm doing this :

long MyInt = 1234;
MyFile << MyInt << std::flush;

This works but the file contains the string "1234", not the binary representation of the long value. I've opened MyFile with ios::binary, but that doesn't seem to be the trick. How do I write to this file so it contains the actualy binary representation of a long variable?

Thanks in advance,
Doug Farrell

3 replies

by bbuscher

The << operator of the ofstream class always convert numbers to printable characters. You can change the base for the number displayed using ios::dec, ios::hex, etc. I am sure you already looked into this and found that there is not ios::bin. This wouldn't help anyway since this only changes the base for the ASCII characters.

There are three ways to write true binary data.
1. use the cout.write() function as follows:
cout.write((char*)(&MyInt), sizeof(MyInt));

2. subclass ofstream and over-ride a method so that int types are no longer converted to characters. The hardest part of this approach is finding exactly what to over-ride. #3 May give you a hint to finding the right method to over-ride.

3. Create a class that overrides the << operator as follows:
ofstream& operator << (ofstream& out, Myclass& var){
}

The above method signiture should appear in the new class called Myclass. Then its up to you to write the de-conversion code. Something along the linesof accessing the integer using a char* and feeding to the regular cout<< a char at a time should work, because there is no conversion for characters.

by dfarrell

Thanks,
The write() method was exactly what I was looking for, just never occured to me to look for something like that. Casting a 'struct' to a pointer and telling the method the size of the 'blob' so to speak. Your answer was perfect.

Doug

This discussion is closed to new replies.