append.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // append.cpp -- appending information to a file
  2. #include <iostream>
  3. #include <fstream>
  4. #include <string>
  5. #include <cstdlib> // (or stdlib.h) for exit()
  6. const char * file = "guests.txt";
  7. int main()
  8. {
  9. using namespace std;
  10. char ch;
  11. // show initial contents
  12. ifstream fin;
  13. fin.open(file);
  14. if (fin.is_open())
  15. {
  16. cout << "Here are the current contents of the "
  17. << file << " file:\n";
  18. while (fin.get(ch))
  19. cout << ch;
  20. fin.close();
  21. }
  22. // add new names
  23. ofstream fout(file, ios::out | ios::app);
  24. if (!fout.is_open())
  25. {
  26. cerr << "Can't open " << file << " file for output.\n";
  27. exit(EXIT_FAILURE);
  28. }
  29. cout << "Enter guest names (enter a blank line to quit):\n";
  30. string name;
  31. while (getline(cin,name) && name.size() > 0)
  32. {
  33. fout << name << endl;
  34. }
  35. fout.close();
  36. // show revised file
  37. fin.clear(); // not necessary for some compilers
  38. fin.open(file);
  39. if (fin.is_open())
  40. {
  41. cout << "Here are the new contents of the "
  42. << file << " file:\n";
  43. while (fin.get(ch))
  44. cout << ch;
  45. fin.close();
  46. }
  47. cout << "Done.\n";
  48. // cin.get();
  49. return 0;
  50. }