Streams were originally designed for text, so the default output mode is text. In text mode, the newline character (hexadecimal 10) expands to a carriage return–linefeed (16-bit only). The expansion can cause problems, as shown here:
#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 }; instead, it outputs { 99, 0, 13, 10, 0 }, which causes problems for a program expecting binary input. If you need true binary output, in which characters are written untranslated, you have several choices:
ofstream ofs ( "test.dat" );
ofs.setmode( filebuf::binary );
ofs.write( char*iarray, 4 ); // Exactly 4 bytes written
#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
}
ofs << binary;
Use the text manipulator to switch the stream to text translation mode.
filedesc fd = _open( "test.dat",
_O_BINARY | _O_CREAT | _O_WRONLY );
ofstream ofs( fd );
ofs.write( ( char* ) iarray, 4 ); // Exactly 4 bytes written