Reading and writing binary structures in C++.


Source listing
//-----------------------------------------------------------------------
// File: Code607_FileIO.cpp
// Purpose: Demonstration of binary (structures) I/O in ANSI Standard C++
// Programming Language: C++
// Author: Dr. Rick Coleman
//------------------------------------------------------------------------
#include <fstream>

using namespace std;


struct simple
{
    int x;
    char ch;
};

int main(void)
{
    ofstream outfile;    // Output file stream
    ifstream infile;    // Input file stream
    simple sim1;

    outfile.open("StructBin.dat", ofstream::binary); 
    if(!outfile.is_open())
    {
       cout << "Unable to open file for output." 
               << "Program terminating.\n";
       return 0;
    }
    //--------------------------------------------------------
    //  Writing structures in binary to a file
    //  I/O function:  outfile.write(const char *, int size)
    //--------------------------------------------------------
    for(int outst=0; outst<10; outst++)
    {
       sim1.x = outst;
       sim1.ch = 'a' + outst;

    // Write 1 structure to the file. Note: the write() function 
    // expects a const char* as the first argument.  We use the 
    // reinterpret_cast operator to cast the structure pointer to a 
    // const char*.  Or just simply use (const char *) as in
    // outfile.write((const char *)(&sim1),sizeof(simple));
       outfile.write(reinterpret_cast(&sim1), 
                    sizeof(simple));  
    }
    outfile.close();

    infile.open("StructBin.dat", ifstream::binary);
    if(!infile.is_open())
    {
        cout << "Unable to open file for input." <<
                     "Program terminating.\n";
        return 0;
    }
    //--------------------------------------------------------
    //  Reading structures in binary from a file
    //  I/O function:  infile.read(char *, int size)
    //--------------------------------------------------------
    while(!infile.eof()) 
    {
    // Read 1 structure from the file. Note: the read() function 
    // expects a char* as the first argument.  We use the 
    // reinterpret_cast operator to cast the structure pointer to a 
    // char*.  Or just simply use (char *) as in
    // infile.read((char *)(&sim1),sizeof(simple));
        infile.read(reinterpret_cast(&sim1), 
            sizeof(simple));
        if(!infile.eof())
            cout << sim1.x << " -- " << sim1.ch << "\n";  
    }
    infile.close();
    return 0;
}