130bool atomicWriteFile(
const std::filesystem::path& targetPath, std::string_view contents,
133 if (targetPath.empty())
136 *errOut =
"atomicWriteFile: empty target path";
146 auto tmp = targetPath;
147 tmp += buildTempSuffix();
161 for (
int attempt = 0; attempt < 8; ++attempt)
166 tmp += buildTempSuffix();
168 fd = ::open(tmp.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
170 if (fd >= 0 || errno != EEXIST)
177 *errOut =
"open(" + tmp.string() +
") failed: ";
178 *errOut += std::strerror(errno);
185 const char* data = contents.data();
186 size_t remaining = contents.size();
187 while (remaining > 0)
189 ssize_t n = ::write(fd, data, remaining);
200 std::error_code rmEc;
201 std::filesystem::remove(tmp, rmEc);
204 *errOut =
"write(" + tmp.string() +
") failed: ";
205 *errOut += std::strerror(saved);
211 remaining -=
static_cast<size_t>(n);
214 if (::fsync(fd) != 0)
221 cleanupTempFile(tmp);
224 *errOut =
"fsync(" + tmp.string() +
") failed: ";
225 *errOut += std::strerror(saved);
230 if (::close(fd) != 0)
236 cleanupTempFile(tmp);
239 *errOut =
"close(" + tmp.string() +
") failed: ";
240 *errOut += std::strerror(saved);
248 std::error_code renameEc;
249 std::filesystem::rename(tmp, targetPath, renameEc);
254 cleanupTempFile(tmp);
257 *errOut =
"rename(" + tmp.string() +
" -> " + targetPath.string() +
258 ") failed: " + renameEc.message();
265 fsyncParentDir(targetPath);
276 std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
280 *errOut =
"open(" + tmp.string() +
") failed";
283 out.write(contents.data(),
static_cast<std::streamsize
>(contents.size()));
289 std::error_code rmEc;
290 std::filesystem::remove(tmp, rmEc);
292 *errOut =
"write to " + tmp.string() +
" failed";
298 std::error_code rmEc;
299 std::filesystem::remove(tmp, rmEc);
301 *errOut =
"close(" + tmp.string() +
") failed (flush error)";
305 std::error_code renameEc;
306 std::filesystem::rename(tmp, targetPath, renameEc);
310 std::error_code rmEc;
311 std::filesystem::remove(tmp, rmEc);
313 *errOut =
"rename failed: " + renameEc.message();
bool atomicWriteFile(const std::filesystem::path &targetPath, std::string_view contents, std::string *errOut=nullptr)
Atomically and durably write contents to targetPath.