Skip to content

write_atomic

Writes contents to path so that readers see either the old file or the new one, never a half-written one.

The data goes to a temporary file in the same directory (so the last step stays on one file system), is flushed to disk, and is then renamed over path. If anything fails the temporary file is removed and path is left as it was. The parent directory must exist.

use helpers4::fs::write_atomic;

Cargo feature fs (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features fs

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.6", default-features = false, features = ["fs"] }
pub fn write_atomic(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> io::Result<()>
ParameterTypeDescription
pathimpl AsRef<Path>The file to create or replace.
contentsimpl AsRef<[u8]>The bytes to write.

io::Result<()>

An io::Error when path has no file name, the temporary file cannot be created or written, or the final rename fails (for instance because path is a directory).

use helpers4::fs::write_atomic;

let path = std::env::temp_dir().join("helpers4-write-atomic-doc.txt");
write_atomic(&path, "first")?;
write_atomic(&path, "second")?;
assert_eq!(std::fs::read_to_string(&path)?, "second");

src/fs/write_atomic.rs