Expand description
A rename that never replaces what is already at the new name.
std::fs::rename replaces an existing destination on every platform, so “check that the name is free, then
rename” lets something created in between be replaced, and its content is gone. rename_no_replace makes
the check and the rename one step:
- Linux:
renameat2withRENAME_NOREPLACE. - macOS:
renamex_npwithRENAME_EXCL. - Windows:
MoveFileExWwithoutMOVEFILE_REPLACE_EXISTING.
An old kernel, or a filesystem that has no such rename (NFS, some FUSE mounts, FAT and exFAT volumes on macOS), is renamed in steps whose first one takes the new name and fails if it is taken:
- A folder: an empty folder is made at the new name, and the folder is renamed over it. A rename over a folder that got something in it meanwhile fails, so nothing put there is lost.
- Anything else: a hard link is made at the new name, then the old name is removed.
- Where hard links can’t be made either: an empty file is made at the new name, exclusively, and the file is renamed over it. Whatever was there already, and whatever anything that does not overwrite files creates there meanwhile, is kept. Only a program that overwrites that empty file in the instant before the rename loses what it wrote: such a filesystem has nothing that closes that last gap.
Either way the caller gets AlreadyExists for a name that is taken, and the person is told the name
already exists.
srv renames local files through this too, so a host and this computer follow one rule.
Functions§
- rename_
no_ replace - Rename
fromtoto, failing withAlreadyExistsinstead of replacing an existingto(a file, a folder, even an empty one, or a link, even a dangling one).