在 linux 上原子写入文件

Atomic writing to file on linux

有没有办法自动将缓冲区转储到文件?

"atomically" 我的意思是:如果有人在写入过程中终止了我的应用程序,我希望文件处于写入前或写入后状态,但不处于损坏的中间状态。

如果答案是"no",那么可能它可以用非常小的缓冲区来完成? 例如,我是否可以使用单个 8 字节 fwrite(在 x64 平台上)转储 2 个后续 int32_t 变量,并确保转储这两个 int32,或者两者都不转储,但不仅仅是其中一个?

我建议写入临时文件,然后对其执行 rename(2)

ofstream o("file.tmp"); //Write to a temporary file
o << "my data";
o.close();

//Perform an atomic move operation... needed so readers can't open a partially written file
rename("file.tmp", "file.real");