Reading and writing binary numbers in C++.


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

using namespace std;


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

    outfile.open("binfile.dat", ofstream::binary);
    //-----------------------------------------------
    //  Writing numerical data as binary to a file
    //  I/O function:  Overloaded << operator
    //-----------------------------------------------
    for(int i=0; i<10; i++)
    {
        outfile << i << " \n";
    }
    outfile.close();

    infile.open("binfile.dat ", ifstream::binary);
    //-----------------------------------------------
    //  Reading numerical data as binary from a file
    //  I/O function:  Overloaded >> operator
    //-----------------------------------------------
    while (infile.good())
    {
        infile >> num;
        if(infile.good()) cout << num << " \n";
    }
    infile.close();
    return 0;
}