Sign in to follow this  
SunTzu

STL file IO [Solved]

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
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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this