STL file IO [Solved]

Started by
5 comments, last by xstreme2000 17 years, 9 months ago
Can anybody explain to me why the following code behaves differently depending on whether it's using the ofstream stuff, or old C-style FILE* stuff?

    string filename = "C:\\test.bin";
    int value = 7;

#if USE_OFSTREAM_STUFF

    ofstream outputFile;

    outputFile.open( filename.c_str(), ios_base::out | ios_base::binary );

    if ( outputFile.is_open() )
    {
        outputFile << value;
        outputFile.close();
    }

#else

    FILE* outputFile;

    outputFile = fopen( filename.c_str(), "wb" );

    if ( outputFile )
    {
        fwrite( &value, sizeof(value), 1, outputFile );
        fclose( outputFile );
    }

#endif
In either case I would expect to end up with a four-byte binary file containing the value 0x0000007, but I only get that in the FILE* case. Using ofstream (even though I have specified ios_base::binary) I end up with an ASCII file containing the single character '7'. Why is this? How should I be writing as binary data using ofstream if not using ios_base::binary? Thanks.
Advertisement
change...

outputFile << value;

to

outputFile.write(&value, sizeof(value));
Rather than using
outputFile << value;
you need to use the "write" member function:
outputFile.write(reinterpret_cast<char *>&value, sizeof(value));


You can see that this corresponds much more closely to your "fwrite" call. Using the insertion operator ('<<') corresponds to using fprintf.
operator<<() and operator>>() operate on text-only files. That's why you get text. Instead, do something like this to mirror the other version:
file.write((char*)&value, sizeof(value));

fstream::write() and fstream::read() pretty much mirror fread() and fwrite() for FILE*s.
The binary flag for iostreams (and for FILE * for that matter) only refers to newline translations. Ex: if \n gets turned into \r\n. The iostream code you have uses operator<< for output which is the formatted output operator, this writes the number converted to a human readable string to the stream. It would be the same as if you used printf("%d",...) on the FILE *. Similarly your FILE * code would write the binary representation of value to the FILE * even if you opened the file in text mode.
That would explain it, thankyou all.
oops, sorry, I forgot the typecast in my reply :(

This topic is closed to new replies.

Advertisement