16.5 Binary IO

I l @ ve RuBoard

16.5 Binary I/O

Binary I/O is accomplished through two member functions: read and write . The syntax for read is:

   in_file   .read(   data_ptr   ,   size   ); 
data_ptr

Pointer to a place to put the data.

size

Number of bytes to be read.

The member function gcount returns the number of bytes gotten by the last read . This may be less than the number of bytes requested . For example, the read might encounter an end-of-file or error:

 struct {      int     width;      int     height;  } rectangle;  in_file.read(static_cast<char *>(&rectangle), sizeof(rectangle)); if (in_file.bad(  )) {     cerr << "Unable to read rectangle\n";      exit (8);  }  if (in_file.gcount(  ) != sizeof(rectangle)) {     cerr << "Error: Unable to read full rectangle\n";     cerr << "I/O error of EOF encountered\n"; } 

In this example you are reading in the structure rectangle . The & operator makes rectangle into a pointer. The cast static_cast<char *> is needed since read wants a character array. The sizeof operator is used to determine how many bytes to read as well as to check that read was successful.

The member function write has a calling sequence similar to read :

 out_file.write(   data_ptr   ,   size   ); 
I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net