Loading...
Searching...
No Matches
AtomicFile.h
Go to the documentation of this file.
1// SPDX-License-Identifier: BSD-3-Clause
2#pragma once
3
4#include <cstdio>
5#include <cstdlib>
6#include <string>
7#include <vector>
8
9#ifdef _WIN32
10#include <fcntl.h>
11#include <io.h>
12#include <sys/stat.h>
13#ifndef NOMINMAX
14#define NOMINMAX
15#endif
16#include <windows.h>
17#else
18#include <unistd.h>
19#endif
20
21namespace eonc::helpers {
22
23// The destination names only complete, flushed files. The temporary file lives
24// beside it so replacement cannot cross a filesystem boundary.
25template <typename Writer>
26bool atomicWriteFile(const std::string &path, Writer writer) {
27 std::string pattern = path + ".tmp.XXXXXX";
28 std::vector<char> name(pattern.begin(), pattern.end());
29 name.push_back('\0');
30#ifdef _WIN32
31 if (_mktemp_s(name.data(), name.size()) != 0) {
32 return false;
33 }
34 int fd = _open(name.data(), _O_CREAT | _O_EXCL | _O_WRONLY | _O_BINARY,
35 _S_IREAD | _S_IWRITE);
36#else
37 int fd = mkstemp(name.data());
38#endif
39 if (fd < 0) {
40 return false;
41 }
42#ifdef _WIN32
43 FILE *file = _fdopen(fd, "wb");
44#else
45 FILE *file = fdopen(fd, "wb");
46#endif
47 if (!file) {
48#ifdef _WIN32
49 _close(fd);
50#else
51 close(fd);
52#endif
53 std::remove(name.data());
54 return false;
55 }
56 bool ok = false;
57 try {
58 ok = writer(file) && !std::ferror(file) && std::fflush(file) == 0;
59 } catch (...) {
60 std::fclose(file);
61 std::remove(name.data());
62 throw;
63 }
64#ifdef _WIN32
65 if (ok) {
66 ok = _commit(fd) == 0;
67 }
68#else
69 if (ok) {
70 ok = fsync(fd) == 0;
71 }
72#endif
73 if (std::fclose(file) != 0) {
74 ok = false;
75 }
76 if (ok) {
77#ifdef _WIN32
78 ok = MoveFileExA(name.data(), path.c_str(),
79 MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
80#else
81 ok = std::rename(name.data(), path.c_str()) == 0;
82#endif
83 }
84 if (!ok) {
85 std::remove(name.data());
86 }
87 return ok;
88}
89
90} // namespace eonc::helpers
bool atomicWriteFile(const std::string &path, Writer writer)
Definition AtomicFile.h:26