// 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(())
}
Create a free account and build your private vault. Share publicly whenever you want.