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:
- Create
name.tmpin the same folder as the target (a rename across volumes is a copy). - Write all the data and call
sync_all()so the bytes are pushed to disk. fs::rename(tmp, target), which replaces the old file.
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)
}second version
leftover temp file: falseOn 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_alland assumingwrite_allmeans "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.
Related questions#
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#
- std::fs::rename: https://doc.rust-lang.org/std/fs/fn.rename.html (read 2026-12-05)
- std::fs::File::sync_all: https://doc.rust-lang.org/std/fs/struct.File.html#method.sync_all (read 2026-12-05)