Binary Output Files

Streams were originally designed for text, and thus text mode is the default output mode. In text mode, a newline character (hexadecimal 10) always expands to a carriage return–linefeed pair. This expansion could cause problems as shown in Example 10:

Example 10

Example 10 demonstrates one of the chief characteristics of text file output.

// exios110.cpp

#include <fstream.h>

int iarray[2] = { 99, 10 };

void main()

{

ofstream os( "test.dat" );

os.write( (char *) iarray, sizeof( iarray ) );

}

You might expect this program to output the byte sequence { 99, 0, 10, 0 }; actually it outputs the sequence { 99, 0, 13, 10, 0 }. This would clearly cause problems for another program that expected binary input.

If you need true binary output, in which characters are written untranslated, then you have several choices, as shown in Examples 11, 12 and 13.

Example 11

You can specify binary output by using the ofstream constuctor mode parameter as shown:

// exios111.cpp

// Binary example 1

#include <fstream.h>

#include <fcntl.h>

#include <io.h>

int iarray[2] = { 99, 10 };

void main()

{

ofstream os( "test.dat", ios::binary );

ofs.write( iarray, 4 ); // Exactly 4 bytes written

}

Example 12

You can construct a stream in the usual way, and then use the setmode member function. This function allows you to change the mode after you have opened the file.

// exios112.cpp

// Binary example 2

#include <fstream.h>

int iarray[2] = { 99, 10 };

void main()

{

ofstream ofs ( "test.dat" );

ofs.setmode( filebuf::binary );

ofs.write( char*iarray, 4 );

// Exactly 4 bytes written

}

As an alternative to the setmode member function, you can use the binary manipulator:

ofs << binary;

There is a companion text manipulator that switches the stream back to text translation mode.

Example 13

Finally, you can first open the file using the C run-time library _open function with a binary mode flag:

// exios113.cpp

// Binary example 3

#include <fstream.h>

#include <fcntl.h>

#include <io.h>

int iarray[2] = { 99, 10 };

void main()

{

filedesc fd = _open( "test.dat",

_O_BINARY | _O_CREAT | _O_WRONLY );

ofstream ofs( fd );

ofs.write( char*iarray, 4 ); // Exactly 4 bytes written

}