Search code examples
c++linuxfilefile-writing

Atomic writing to file on linux


Is there a way to dump a buffer to file atomically?

By "atomically" I mean: if for example someone terminates my application during writing, I'd like to have file in either before- or after-writing state, but not in a corrupted intermediate state.

If the answer is "no", then probably it could be done with a really small buffers? For example, can I dump 2 consequent int32_t variables with a single 8 bytes fwrite (on x64 platform), and be sure that both of those int32s are dumped, or neither of them, but not only just one of them?


Solution

  • I recommend writing to a temporary file and then doing a rename(2) on it.

    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");