Skip to main content

write_atomic

Function write_atomic 

Source
pub fn write_atomic(path: &Path, contents: &[u8]) -> Result<()>
Expand description

Replaces the file at path with contents in one step, creating its directory: a temporary file beside it is written, synced and renamed over it, so a crash or a full disk never leaves it half written. A symlink’s target is replaced and the link kept, and a dangling link’s target is created; an existing file keeps its permissions. A read-only file is refused, as is anything but a regular file, because opening a FIFO or a device for writing can block forever.

Unlike writing in place, the rename needs write access to the directory, gives the file a new inode (a hard link to the old one keeps the old text) and makes this process the file’s owner. A crash between create and rename can leave a .name.<pid>-<n>.tmp beside the file.