Source of textfile_append.cpp


  1: //textfile_append.cpp

  3: #include <iostream>
  4: #include <fstream>
  5: #include <vector>
  6: #include <algorithm>
  7: #include <cstdlib>
  8: using namespace std;

 10: int main()
 11: {
 12:     cout << "\nThis program illustrates how to append new data to an "
 13:         "already-existing\ntextfile from within a C++ program. It also "
 14:         "illustrates the difference\nbetween overwriting an already-"
 15:         "existing file, and appending something\nto that file.";
 16:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 18:     int odds[5]  = {1, 3, 5, 7, 9};
 19:     int evens[5] = {2, 4, 6, 8, 10};
 20:     vector<int> v(5);
 21:     fstream file;

 23:     cout << "\nFirst we copy odd values into a vector and display to "
 24:         "confirm:\n";
 25:     copy(odds, odds+5, v.begin());
 26:     copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); 
 27:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 29:     cout << "\nNext we copy the same odd values from the vector to a "
 30:         "file, \nand display the file contents to confirm:\n";
 31:     file.open("textfile_append.out", ios::out | ios::trunc);
 32:     copy(v.begin(), v.end(), ostream_iterator<int>(file, " ")); 
 33:     file << endl;
 34:     file.close();  file.clear(); //Note this important "idiom".
 35:     system("type textfile_append.out"); system("pause"); //non-portable!

 37:     cout << "\nNow we overwrite the odd values in the vector with even "
 38:         "values, \nthen display the contents of the vector again to "
 39:         "confirm:\n";
 40:     copy(evens, evens+5, v.begin());
 41:     copy (v.begin(), v.end(), ostream_iterator<int>(cout, " ")); 
 42:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 44:     cout << "\nThen we overwrite the file of odd values with a file of "
 45:         "even values,\nand display the file contents again to confirm:\n";
 46:     file.open("textfile_append.out", ios::out | ios::trunc);
 47:     copy(v.begin(), v.end(), ostream_iterator<int>(file, " "));
 48:     file << endl;
 49:     file.close();  file.clear();
 50:     system("type textfile_append.out"); system("pause"); //non-portable!

 52:     cout << "\nFinally, we copy the odd values back into the vector, and "
 53:         "this time we append\nthe contents of the vector to the end of the "
 54:         "file and display the file one more\ntime to show that it now "
 55:         "contains both the even and the odd values.\n";
 56:     copy(odds, odds+5, v.begin());
 57:     file.open("textfile_append.out", ios::out | ios::app);
 58:     copy(v.begin(), v.end(), ostream_iterator<int>(file, " ")); 
 59:     file << endl;
 60:     file.close();  file.clear();
 61:     system("type textfile_append.out"); system("pause"); //non-portable!
 62: }