snippet that atomically writes a file to disk (or overrides existing)
int atomic_write_file_with_tmp(const char* path, const char* tmp_path, const uint8_t* data, size_t size)
{
int fd = open(tmp_path, O_CREAT|O_WRONLY|O_TRUNC | O_EXCL | O_CLOEXEC, 0666);
if (fd < 0) {
return -1;
}
size_t i = 0;
while (i < size) {
ssize_t rc = write(fd, data + i, size - i);
if (rc < 0) {
if (errno == EINTR) {
continue;
}
close(fd);
return -1;
}
i += rc;
}
if (fsync(fd) < 0) {
close(fd);
return -1;
}
close(fd);
if (rename(tmp_path, path) < 0) {
return -1;
}
return 0;
}
tmp file needs to be on same partition to be atomically moves. ideally in same directory, and with random unique name. alternatively linux and other OSs can create anonymous file, so no collisions.
doesn't deal with parent directory creation.