https://rentry.org/PPP2_p391_v2

// Code derived from Stroustrup's PPP2 book
// § 11.3.2 Binary files (v2)
//  -and beginning on p 391

// note: this is an extended & reworked example of the book's original, that
// demonstrates moving data for both the character & binary formats to/from disk
// files, and confirming the resultant data are identical.

#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <vector>

using namespace std;

// needed for binary I/O
template <class T>
char* as_bytes(T& i)
{
  void* addr = &i;  // get the address of the first byte of memory used to
                    // store the object

  return static_cast<char*>(addr);  // treat that memory as bytes
}

//------------------------------------------------------------------------------

int main()
{
  // comparison of some C++ built-in type sizes in bytes:
  cout << "sizeof(char): \t\t" << sizeof(char) << '\n';
  cout << "sizeof(int): \t\t" << sizeof(int) << '\n';
  cout << "sizeof(double): \t" << sizeof(double) << "\n\n";

  //---

  // original source data vector
  vector<int> const ints{2147483647, -2147483648, 2147483647, -2147483648,
                         2147483647};

  // write the source data vector out to both text & binary -formatted files:

  ofstream ost_txt{"ints.txt"};  // text data output
  for (auto i : ints)            //
    ost_txt << i << '\n';        // note: writing chars

  ofstream ost_bin{"ints.bin", ios_base::binary};  // binary data output
  for (auto i : ints)                              //
    ost_bin.write(as_bytes(i), sizeof(int));       // note: writing bytes

  ost_txt.close();  // close both output file streams before proceeding
  ost_bin.close();  //

  //---

  // read in binary data file:

  vector<int> b_ints;

  ifstream ist_bin{"ints.bin", ios_base::binary};       // binary data input
                                                        //
  for (int x; ist_bin.read(as_bytes(x), sizeof(int));)  // note: reading bytes
    b_ints.push_back(x);

  //---

  // display the two vector's data for comparison:

  cout << "source data (using C++ types):\n";
  for (auto i : ints)
    cout << setw(12) << i << '\n';
  cout << '\n';

  cout << "reconstructed data (from binary file):\n";
  for (auto i : b_ints)
    cout << setw(12) << i << '\n';
  cout << '\n';

  cout << " in-memory vector sizes match: " << std::boolalpha
       << (b_ints.size() == ints.size()) << "\n\n";

  //---

  // list the system disk file sizes for comparison
  std::system("ls -hl ints*");  // note: clear diff in sizes for the same data
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_11/main_p391_v2.cpp && ./a.out

PrevUpNext
Original

Edit
Pub: 09 Apr 2023 06:14 UTC
Edit: 14 May 2023 11:39 UTC
Views: 373