FAQ - Help and questions

How do I save a file so a crash or power loss cannot leave it half written?

#files#saving#desktop#reliabilitypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Write the new content to a temporary file in the same folder, flush it to disk with sync_all, then rename it over the real file. A reader then sees either the whole old file or the whole new one. The example was compiled and run on Windows.

Checked with rustc 1.93.0, Windows 11; compiled and run. Only Windows was run; the macOS behaviour of rename is documented by std and POSIX but was not tested here.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

fs::write truncates the file and then writes. If the program or the computer stops in between, the user has a short or empty file and no copy of the old one. For documents and settings that is data loss.

The safe pattern is write to a temporary file, then replace:

  1. Create name.tmp in the same folder as the target (a rename across volumes is a copy).
  2. Write all the data and call sync_all() so the bytes are pushed to disk.
  3. fs::rename(tmp, target), which replaces the old file.
src/main.rsrust
use std::fs;
use std::io::Write;
use std::path::Path;

/// Write `data` to `path` so a crash or power loss leaves either the old file or the new one, never half of each.
fn save_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
    let tmp = path.with_extension("tmp"); // same folder, so the rename stays on one volume
    let mut f = fs::File::create(&tmp)?;
    f.write_all(data)?;
    f.sync_all()?; // ask the OS to push the bytes to disk before the rename
    drop(f);
    fs::rename(&tmp, path) // replaces the old file
}

fn main() -> std::io::Result<()> {
    let dir = std::env::temp_dir().join("rs-forum-save-demo");
    fs::create_dir_all(&dir)?;
    let doc = dir.join("notes.txt");
    save_atomic(&doc, b"first version")?;
    save_atomic(&doc, b"second version")?;
    println!("{}", fs::read_to_string(&doc)?);
    println!("leftover temp file: {}", doc.with_extension("tmp").exists());
    fs::remove_dir_all(&dir)
}
text
second version
leftover temp file: false

On Windows the second save_atomic replaced an existing file, as the output shows. std's documentation says that rename replaces an existing destination on both Windows and Unix, and notes platform differences (for example when the destination is a directory or is open in another program); read the fs::rename page before relying on edge cases.

Common mistakes#

  • Using a fixed temp name in a shared folder. Two saves at once overwrite each other's temp file.
  • Skipping sync_all and assuming write_all means "on disk". It means "handed to the operating system".
  • Keeping the file open elsewhere on Windows. Another program (an editor, a virus scanner) holding the target can make the rename fail; report the error to the user instead of ignoring it.

Should I keep a backup copy too?#

For documents the user cares about, keep one previous version (rename the old file to name.bak before the final rename). It costs disk space and saves the day when the new content turns out to be wrong rather than damaged.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet