Source of binary_file2.cpp


  1: //binary_file2.cpp

  3: #include <iostream>
  4: #include <fstream>
  5: using namespace std;

  7: int main()
  8: {
  9:     cout << "\nThis program reads in the data from binary_file1.txt and "
 10:         "binary_file1.bin,\nallowing the user to compare integer input "
 11:         "from a textfile and a binary file.";
 12:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 14:     ifstream inFileText("binary_file1.txt");
 15:     if (!inFileText)
 16:     {
 17:         cout << "\nError: Could not open binaryfile1.txt.\n"
 18:             "Program now terminating.";
 19:         cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 20:         return 1;
 21:     }

 23:     fstream inFileBinary("binary_file1.bin", ios::in | ios::binary);
 24:     if (!inFileBinary)
 25:     {
 26:         cout << "\nError: Could not open binaryfile1.bin.\n"
 27:             "Program now terminating.";
 28:         cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 29:         inFileText.close();
 30:         return 2;
 31:     }

 33:     int i;
 34:     inFileText >> i;
 35:     cout << "\nValue from the textfile:    " << i;
 36:     inFileBinary.read((char *)&i, sizeof(int));
 37:     cout << "\nValue from the binary file: " << i;
 38:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 40:     inFileText.close();
 41:     inFileBinary.close();
 42: }