Fission FSN
Loading...
Searching...
No Matches
fsSavedFile.h
Go to the documentation of this file.
1#pragma once
2
3// Atomic replacement of saved-data files: write a temporary sibling, flush it to
4// disk, then rename it over the original. An interrupted save leaves the previous
5// file intact, plus a stray .tmp that the next save overwrites.
6
7#include <cstdio>
8#include <filesystem>
9#include <string>
10#include <system_error>
11#ifdef _WIN32
12#include <io.h>
13#else
14#include <unistd.h>
15#endif
16
17namespace fsSavedFile
18{
19inline std::filesystem::path tempPathGet(const std::filesystem::path& pPath)
20{
21 std::filesystem::path temp = pPath;
22 temp += ".tmp";
23 return temp;
24}
25
26// A save killed mid-write leaves its temporary file; remove it with the save itself.
27inline void tempRemove(const std::filesystem::path& pPath)
28{
29 std::error_code error;
30 std::filesystem::remove(tempPathGet(pPath), error);
31}
32
33inline bool save(const std::filesystem::path& pPath, const std::string& pData)
34{
35 const std::filesystem::path temp = tempPathGet(pPath);
36#ifdef _WIN32
37 FILE* const file = _wfopen(temp.c_str(), L"wb");
38#else
39 FILE* const file = std::fopen(temp.c_str(), "wb");
40#endif
41 if (!file)
42 {
43 return false;
44 }
45 bool ok = std::fwrite(pData.data(), 1, pData.size(), file) == pData.size();
46 ok = std::fflush(file) == 0 && ok;
47#ifdef _WIN32
48 ok = _commit(_fileno(file)) == 0 && ok;
49#else
50 ok = ::fsync(fileno(file)) == 0 && ok;
51#endif
52 ok = std::fclose(file) == 0 && ok;
53
54 std::error_code error;
55 if (ok)
56 {
57 // Replaces an existing file in one step (MoveFileEx with REPLACE_EXISTING on Windows).
58 std::filesystem::rename(temp, pPath, error);
59 ok = !error;
60 }
61 if (!ok)
62 {
63 std::filesystem::remove(temp, error);
64 }
65 return ok;
66}
67}
Definition fsSavedFile.h:18
void tempRemove(const std::filesystem::path &pPath)
Definition fsSavedFile.h:27
bool save(const std::filesystem::path &pPath, const std::string &pData)
Definition fsSavedFile.h:33
std::filesystem::path tempPathGet(const std::filesystem::path &pPath)
Definition fsSavedFile.h:19