# How do I save a file so a crash or power loss cannot leave it half written?
Source: https://ruststudio.org/community/t/248/how-do-i-save-a-file-so-a-crash-or-power-loss-cannot-leave-it-half-written
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | 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.
Category: Help and questions | Kind: FAQ | Tags: files, saving, desktop, reliability | Views: 0

## 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.

## Answer
## 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.

```rust title=src/main.rs
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.

## 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)
