January 4, 2002

Reading Binary Data from an ifstream

To read a binary value from an input file stream (ifstream) object, use the read() member function. read() takes two parameters: char * and long, which hold the address of the buffer to which the value is written and its size, respectively. The following code snippet retrieves an int from

Parenthesize Macro Arguments

It’s a good idea to parenthesize every macro argument. For example: #define MAX(x,y) (x)>(y)?(x):(y) The parentheses ensure that the macro is evaluated correctly, even if the user passes complex expressions that contain operators as arguments: int a=0,n=1,b=0,c=0;int q=MAX(a+8-n, b==c?b:c)

Serializing a Polymorphic Object

A polymorphic object has one or more virtual functions. When you serialize such an object to a file so that it can be reconstituted later, the deserialization might rewrite its vptr and cause undefined behavior. To overcome this problem, leave the vptr intact by copying only the user-declared data members

Writing Binary Data to an ofstream

To write the binary value of a variable to an output file stream (ofstream) object, use the write() member function. write() takes two parameters: const char * and long, which hold the address of the variable being written to the file and its size, respectively. The following code snippet writes