// // NBO_file_IO.cpp // // A module to demonstrate reading and writing NBOs to a binary // file. // #include #include #include #include "NBO.h" using namespace std; namespace { const unsigned int NUMBER_COUNT = 40; // // writeNBOs // // Purpose: To write a series of NBOs to a file. The numbers // comprise the first NUMBER_COUNT terms of the // Fibonacci sequence. // Argument(s): // <1> filename: The name of the file // Precondition(s): // <1> filename.compare("") != 0 // Returns: N/A // Side Effect: The first NUMBER_COUNT Fibonacci numbers are // written to a binary file named filename. // void writeNBOs (const string& filename) { NBO fibonacci[NUMBER_COUNT]; ofstream outfile; fibonacci[0] = 0; fibonacci[1] = 1; for(unsigned int i = 2; i < NUMBER_COUNT; i++) fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2]; outfile.open(filename.c_str(), ios::out | ios::binary); for(unsigned int i = 0; i < NUMBER_COUNT; i++) { NBO term = fibonacci[i]; outfile.put(term[0]); outfile.put(term[1]); outfile.put(term[2]); outfile.put(term[3]); } outfile.close(); } // // readNBOs // // Purpose: To write a series of NBOs from an existing binary // file and print them to standard output. // Argument(s): // <1> filename: The name of the file // Precondition(s): // <1> filename.compare("") != 0 // Returns: N/A // Side Effect: The first NUMBER_COUNT numbers are read from // binary file filename and printed to standard // output. // void readNBOs (const string& filename) { ifstream infile; infile.open(filename.c_str(), ios::in | ios::binary); for(unsigned int i = 0; i < NUMBER_COUNT; i++) { NBO number; number[0] = infile.get(); number[1] = infile.get(); number[2] = infile.get(); number[3] = infile.get(); cout << setw(15) << number; if(i % 5 == 4) cout << endl; } infile.close(); } } // end of anonymous namespace int main () { string filename = "Fibonacci.dat"; writeNBOs(filename); readNBOs(filename); return 0; }