binary.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // binary.cpp -- binary file I/O
  2. #include <iostream> // not required by most systems
  3. #include <fstream>
  4. #include <iomanip>
  5. #include <cstdlib> // (or stdlib.h) for exit()
  6. inline void eatline() { while (std::cin.get() != '\n') continue; }
  7. struct planet
  8. {
  9. char name[20]; // name of planet
  10. double population; // its population
  11. double g; // its acceleration of gravity
  12. };
  13. const char * file = "planets.dat";
  14. int main()
  15. {
  16. using namespace std;
  17. planet pl;
  18. cout << fixed << right;
  19. // show initial contents
  20. ifstream fin;
  21. fin.open(file, ios_base::in |ios_base::binary); // binary file
  22. //NOTE: some systems don't accept the ios_base::binary mode
  23. if (fin.is_open())
  24. {
  25. cout << "Here are the current contents of the "
  26. << file << " file:\n";
  27. while (fin.read((char *) &pl, sizeof pl))
  28. {
  29. cout << setw(20) << pl.name << ": "
  30. << setprecision(0) << setw(12) << pl.population
  31. << setprecision(2) << setw(6) << pl.g << endl;
  32. }
  33. fin.close();
  34. }
  35. // add new data
  36. ofstream fout(file,
  37. ios_base::out | ios_base::app | ios_base::binary);
  38. //NOTE: some systems don't accept the ios::binary mode
  39. if (!fout.is_open())
  40. {
  41. cerr << "Can't open " << file << " file for output:\n";
  42. exit(EXIT_FAILURE);
  43. }
  44. cout << "Enter planet name (enter a blank line to quit):\n";
  45. cin.get(pl.name, 20);
  46. while (pl.name[0] != '\0')
  47. {
  48. eatline();
  49. cout << "Enter planetary population: ";
  50. cin >> pl.population;
  51. cout << "Enter planet's acceleration of gravity: ";
  52. cin >> pl.g;
  53. eatline();
  54. fout.write((char *) &pl, sizeof pl);
  55. cout << "Enter planet name (enter a blank line "
  56. "to quit):\n";
  57. cin.get(pl.name, 20);
  58. }
  59. fout.close();
  60. // show revised file
  61. fin.clear(); // not required for some implementations, but won't hurt
  62. fin.open(file, ios_base::in | ios_base::binary);
  63. if (fin.is_open())
  64. {
  65. cout << "Here are the new contents of the "
  66. << file << " file:\n";
  67. while (fin.read((char *) &pl, sizeof pl))
  68. {
  69. cout << setw(20) << pl.name << ": "
  70. << setprecision(0) << setw(12) << pl.population
  71. << setprecision(2) << setw(6) << pl.g << endl;
  72. }
  73. fin.close();
  74. }
  75. cout << "Done.\n";
  76. // keeping output window open
  77. // cin.clear();
  78. // eatline();
  79. // cin.get();
  80. return 0;
  81. }