https://rentry.org/PPP2_p393

// Code derived from Stroustrup's PPP2 book
// § 11.3.3 Positioning in files
//  -and beginning on p 393

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

using namespace std;

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

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

int main()
try {
  string const name{"points.txt"};

  fstream fs{name};  // open for input and output
  if (! fs)
    error("can't open ", name);

  fs.seekg(5);  // move reading position (g for “get”) to 5 (the 6th character)

  char ch;
  fs >> ch;  // read and increment reading position
  cout << "character[5] is '" << ch << "' (" << int(ch) << ")\n";

  fs.seekp(1);  // move writing position (p for “put”) to 1
  fs << '4';    // write and increment writing position

} 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_p393.cpp && ./a.out

PrevUpNext

Edit
Pub: 09 Apr 2023 05:52 UTC
Edit: 03 May 2023 10:30 UTC
Views: 340