// Created on savesnippets.com · https://savesnippets.com/wo4vvcz6Uue4l9 // Cargo.toml: tempfile = "3" use std::io::{self, Write}; use std::path::Path; use tempfile::NamedTempFile; fn atomic_write(path: impl AsRef, 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(()) }