DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
iostream examples

Binary output

Sometimes a program needs to output binary data or a single character.

   int c='A' ;
   cout.put(c) ;
   cout << (char)c ;
The last two lines are equivalent. Each inserts a single character (A) into cout.

If we want to output a larger object in its binary form a loop using put would be possible, but a more efficient method is to use the write member. For example:

   cout.write((char*)&x, sizeof(x))

will output the raw binary form of x.

The reader should notice that the above example violates C++ type discipline by converting &x to char*. Sometimes this is harmless, but if the type of x is a class with virtual member functions, or one that requires non-trivial constructor actions, the value written by the above cannot be read back in properly.


Next topic: Input
Previous topic: Flushing

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 02 June 2005