https://rentry.org/PPP2_p391

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

#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

using namespace std;

void error(string const& s) { throw runtime_error(s); }
void error(string const& s1, string const& s2) { error(s1 + s2); }

// 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()
try {
  // open an istream for binary input from a file:
  cout << "Please enter input file name\n";
  string iname;
  cin >> iname;

  // binary tells the stream not to try anything clever with the bytes
  ifstream ifs{iname, ios_base::binary};  // note: stream mode is binary
  if (! ifs)
    error("can't open input file ", iname);

  // open an ostream for binary output to a file:
  cout << "Please enter output file name\n";
  string oname;
  cin >> oname;

  // binary tells the stream not to try anything clever with the bytes
  ofstream ofs{oname, ios_base::binary};  // note: stream mode is binary
  if (! ofs)
    error("can't open output file ", oname);

  // read from binary file:
  vector<int> v;
  for (int x; ifs.read(as_bytes(x), sizeof(int));)  // note: reading bytes
    v.push_back(x);

  // . . . do something with v . . .

  // write to binary file:
  for (int x : v)
    ofs.write(as_bytes(x), sizeof(int));  // note: writing bytes

} catch (exception const& e) {
  cerr << "error: " << e.what() << '\n';
  return 1;

} catch (...) {
  cerr << "Oops: unknown exception!\n";
  return 2;
}

build & run:

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

PrevUpNext
Bonus

Edit
Pub: 09 Apr 2023 05:49 UTC
Edit: 03 May 2023 10:28 UTC
Views: 375