std.fs.replace

std.fs

replace(path, text, mode) -> ok, err

Put a file's new bytes in place in one step

Writes text to a new file beside path, syncs it and renames it over path, then syncs the directory. The new file is born 0600, and mode, an octal string such as "0644", is set on it before the sync. A text that is not a string, or a mode of any other shape, raises, and nothing is written.

A reader of path sees the old file or the new one, never part of either. Answers true once the directory is synced: the new file then survives a power loss as well as a crash.

A refusal answers nil and the errno text. Before the rename, a refusal removes the new file, and the old one stays whole. A refused sync_dir after the rename answers nil too, though the new file is already in place: its name may not survive a power loss.

The new file is .<name>.<hex>.tmp in the same directory, made with open_private, so no other user can read it, and a link planted at that name is refused. A path that is a symlink is replaced by the file, and its target is left alone. Two calls on one path at once each write their own file, and the last rename wins.

replace does not suit a file that must be made only once, such as a key two processes may race to create: the second rename would put its key over the first. Make that file with open_private and sync it.