foxygit / Torlinkc Log in
commits tags

/src/util/atomic_write.cpp · 828 B

raw
#include "torlinkc/util/atomic_write.hpp"

#include <cstdio>
#include <filesystem>
#include <fstream>
#include <stdexcept>

namespace fs = std::filesystem;

namespace torlinkc {

void writeJsonAtomic(const std::string& file, const nlohmann::json& data) {
  fs::path path(file);
  fs::create_directories(path.parent_path());

  fs::path tmp = path;
  tmp += ".tmp";

  {
    std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
    if (!out) throw std::runtime_error("failed to open " + tmp.string() + " for writing");
    out << data.dump(2);
    if (!out) throw std::runtime_error("failed to write " + tmp.string());
  }

  std::error_code ec;
  fs::rename(tmp, path, ec);
  if (ec) throw std::runtime_error("failed to rename " + tmp.string() + " to " + path.string() + ": " + ec.message());
}

}  // namespace torlinkc