#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
namespace fs = std::filesystem;
void save(const fs::path &target, const std::string &text, bool fail) {
  const auto temporary = target.string() + ".pending";
  if (fs::exists(temporary))
    throw std::runtime_error("Temporary file occupied");
  try {
    std::ofstream out(temporary, std::ios::binary);
    out.exceptions(std::ios::badbit | std::ios::failbit);
    out << text;
    out.flush();
    out.close();
    if (fail)
      throw std::runtime_error("Injected failure");
    fs::rename(temporary, target);
  } catch (...) {
    std::error_code ignored;
    fs::remove(temporary, ignored);
    throw;
  }
}
std::string read(const fs::path &p) {
  std::ifstream in(p);
  return {std::istreambuf_iterator<char>(in), {}};
}
int main() {
  const fs::path target = "learning-record.txt";
  if (fs::exists(target))
    throw std::runtime_error("Use a fresh learning folder");
  save(target, "old", false);
  try {
    save(target, "new", true);
    throw std::logic_error("Failure not raised");
  } catch (const std::runtime_error &) {
  }
  if (read(target) != "old")
    throw std::runtime_error("Old value lost");
  save(target, "new", false);
  if (read(target) != "new")
    throw std::runtime_error("New value missing");
  fs::remove(target);
  std::cout << "failure and replacement verified\n";
}
