Is there a non-platform-specific way of doing an atomic "rename File1 to File2 if File2 does not exist, otherwise give an error"? I know I could just check whether File2 exists, then rename the file if it doesn't, but this introduces a potential race condition when some other process creates File2 between the check and the rename()
.
Under Linux there is the renameat2()
function which does exactly this with the RENAME_NOREPLACE
flag set. Unfortunately, the manpage says
renameat2() is Linux-specific.
I don't even know whether all libc implementations support this call, or only glibc.
For my usecase, renaming inside the same directory is enough, I don't need to have support for moving to a whole different path.
This is potentially related to https://stackoverflow.com/a/230581/5562035 and Atomically swap contents of two files on Linux