https://rentry.org/PPP2_p389

// Code derived from Stroustrup's PPP2 book
// § 11.3.1 File open modes
//  -and beginning on p 389

#include <fstream>

using namespace std;

int main()
{
  const char* name1 = "myfile1";
  const char* name2 = "myfile2";
  const char* name  = "myfile0";

  ofstream of1{name1};                // defaults to ios_base::out
  ifstream if1{name2};                // defaults to ios_base::in
  ofstream ofs{name, ios_base::app};  // ofstreams by default include
                                      // io_base::out
  fstream fs{"myfile", ios_base::in | ios_base::out};  // both in and out
  if (! fs) {
    ;  // oops: we couldn’t open that file that way
  }

  ifstream ifs{"redungs"};
  if (! ifs) {
    ;  // error: can’t open “readings” for reading
  }

  {
    ofstream ofs{"no-such-file"};  // create new file called no-such-file
    ifstream ifs{"no-file-of-this-name"};  // error: ifs will not be good()
  }
}

build & run:

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

PrevUpNext

Edit
Pub: 09 Apr 2023 05:09 UTC
Edit: 03 May 2023 10:27 UTC
Views: 356