Source of binary_file5.cpp


  1: //binary_file5.cpp
  2: //Illustrates a binary file of integers:
  3: //Creating, then reading and modifying with direct (or "random") access.

  5: #include <iostream>
  6: #include <fstream>
  7: using namespace std;

  9: int main()
 10: {
 11:     int NUMBER_OF_BYTES_IN_INT = sizeof(int);
 12:     fstream file("binary_file5.bin",
 13:         ios::binary | ios::trunc | ios::in | ios::out);

 15:     int a[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24};
 16:     for (int i=0; i<12; i++)
 17:         file.write((char *)&a[i], NUMBER_OF_BYTES_IN_INT);
 18:     cout << "\nThe first 12 positive even integers have been"
 19:         "\nwritten to a binary file called binary_file5.bin.";
 20:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 22:     cout << "\nHere are those integers, as read from the file:\n";
 23:     file.seekg(0);
 24:     while (file)
 25:     {
 26:         int k;
 27:         file.read((char *)&k, NUMBER_OF_BYTES_IN_INT);
 28:         if (file) cout << k << " ";
 29:     }
 30:     file.clear();
 31:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 33:     cout << "\nNow we read and display the 10th integer, directly from "
 34:         "the file.\nThen we overwrite that value with its square."
 35:         "\nFinally, we display all the values again to show the revision.";
 36:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 37:     file.seekg(9*NUMBER_OF_BYTES_IN_INT, ios::beg);
 38:     int n;
 39:     file.read((char *)&n, NUMBER_OF_BYTES_IN_INT);
 40:     cout << "\nHere's the 10th value: " << n << endl;
 41:     n *= n;
 42:     file.seekg(-NUMBER_OF_BYTES_IN_INT, ios::cur);
 43:     file.write((char *)&n, NUMBER_OF_BYTES_IN_INT);

 45:     cout << "And here are the integers again, showing the value "
 46:         "we squared:\n";
 47:     file.seekg(0);
 48:     while (file)
 49:     {
 50:         int k;
 51:         file.read((char *)&k, NUMBER_OF_BYTES_IN_INT);
 52:         if (file) cout << k << " ";
 53:     }
 54:     file.close();  file.clear();
 55:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 56: }