https://rentry.org/PPP2_p352

// Code derived from Stroustrup's PPP2 book
// § 10.4 Opening a file
//  -and beginning on p 352

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

using namespace std;

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

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

int main()
try {
  ifstream ifs;
  string   name = "chapter.10.4-problematic.foo";
  // ...
  string foo;
  ifs >> foo;  // won't succeed: no file opened for ifs
  // ...
  ifs.open(name, ios_base::in);  // open file named name for reading
  // ...
  ifs.close();  // close file
  // ...
  string bar;
  ifs >> bar;  // won't succeed: ifs' file was closed
  // ...

  fstream fs;
  fs.open("foo", ios_base::in);  // open for input
  // close() missing
  fs.open("foo", ios_base::in);  // won't succeed: ifs is already open
  if (! fs)
    error("impossible");

} catch (exception& 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_10/main_p352.cpp && ./a.out

PrevUpNext

Edit
Pub: 07 Apr 2023 21:59 UTC
Edit: 03 May 2023 09:42 UTC
Views: 349