Writing Bytes with ostream Member Function write

When writing the integer number to a file, instead of using the statement

outFile << number;

which for a four-byte integer could print as few digits as one or as many as 11 (10 digits plus a sign, each requiring a single byte of storage), we can use the statement

outFile.write( reinterpret_cast< const char * >( &number ),   sizeof( number ) );

which always writes the binary version of the integer number’s four bytes (on a machine with four-byte integers). Function write treats its first argument as a group of bytes by viewing the object in memory as a const char *, which is a pointer to a byte. Starting from that location, function write outputs the number of bytes ...

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.