• Advertisement
Sign in to follow this  

STL file IO [Solved]

This topic is 4201 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

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.

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement