Rust

Atomic File Write (tempfile + persist)

admin by @admin ADMIN
20h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Write to a temp file in the SAME directory, then atomically `persist` (rename). The `tempfile` crate handles cleanup if you crash before persisting.
Rust
Raw
// Cargo.toml: tempfile = "3"
use std::io::{self, Write};
use std::path::Path;
use tempfile::NamedTempFile;

fn atomic_write(path: impl AsRef<Path>, data: &[u8]) -> io::Result<()> {
    let path = path.as_ref();
    let dir  = path.parent().unwrap_or_else(|| Path::new("."));

    let mut tmp = NamedTempFile::new_in(dir)?;
    tmp.write_all(data)?;
    tmp.as_file().sync_all()?;            // fsync — durability before rename
    tmp.persist(path)?;                   // atomic rename on POSIX
    Ok(())
}

fn main() -> io::Result<()> {
    atomic_write("/var/lib/myapp/state.json", b"{\"ok\":true}\n")?;
    Ok(())
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.