← C++

C++ · 14 / 24

Test failure-tolerant file operations

Keep the previous file contents intact when a preparatory write fails.

  • Large
  • Advanced
  • 90 min

Prerequisites: Classes, references, const and RAII, Headers, CMake and first unit tests, Map editing, undo/redo and safe project files

In this tutorial
  1. Define the contract
  2. Separate tools and build
  3. Check observable expectations
  4. Detect an incorrect change
  5. Run the exercise separately
  6. Interpret the verification boundary
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

GCC with C++20 and CMake 3.25 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-21 on Linux x86_64. Check successful replacement and failure when the temporary path already exists. Existing data must survive. Multiple writers require an additional synchronization and naming strategy.

The previous file is replaced only after preparation succeeds. Failure is injected before rename. This example assumes one writer in a private Linux learning directory. It claims neither power-loss durability nor identical replacement semantics across platforms. FactoryForge uses QSaveFile for this boundary.

Package contents and individual files

01Define the contract

A temporary file is written first. Only a successful write is followed by rename to replace the target. The example assumes a single writer. It promises neither a transaction across files nor durability after power loss.

main.cpp · cppOpen file
#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";
}

Run / check

python3 verify.py

02Separate tools and build

Put all files in a new folder. Read the compiler options and run verify.py. A failed command must propagate its exit code to the caller.

verify.py · pyOpen file
import subprocess

subprocess.run(["cmake", "-S", ".", "-B", "build"], check=True)
subprocess.run(["cmake", "--build", "build", "--config", "Release"], check=True)
subprocess.run(
    ["ctest", "--test-dir", "build", "-C", "Release", "--output-on-failure"], check=True
)

03Check observable expectations

Check successful replacement and failure when the temporary path already exists. Existing data must survive. Multiple writers require an additional synchronization and naming strategy.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.20)
project(learning LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(lesson main.cpp)
enable_testing()
add_test(NAME behaviour COMMAND lesson)
Expected result

Check successful replacement and failure when the temporary path already exists. Existing data must survive. Multiple writers require an additional synchronization and naming strategy.

04Detect an incorrect change

Change a checked condition or expected result. Verification must now fail. Restore the original version afterwards. A green process alone does not explain which property is protected.

05Run the exercise separately

Create a .pending file before save. The call must fail and preserve that existing file.

06Interpret the verification boundary

The collision check is before the try block. Cleanup therefore does not remove a file it did not create. For multiple processes the pre-check is insufficient. Exclusive file creation is then required.

Expected result

Verification finishes successfully and checks the conditions named in the example.

Your exercise

Create a .pending file before save. The call must fail and preserve that existing file.

Show the solution and explanation

The collision check is before the try block. Cleanup therefore does not remove a file it did not create. For multiple processes the pre-check is insufficient. Exclusive file creation is then required.

solution.cpp · cppOpen file
#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::ofstream occupied("learning-record.txt.pending");
    occupied << "keep";
  }
  try {
    save("learning-record.txt", "other", false);
    throw std::logic_error("Accepted collision");
  } catch (const std::runtime_error &) {
  }
  if (read("learning-record.txt.pending") != "keep")
    throw std::runtime_error("Existing file changed");
  fs::remove("learning-record.txt.pending");
  std::cout << "failure and replacement verified\n";
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.