...
This code example is non-compliant because if the any existing destination file exists it is removed by rename()
.
Code Block | ||
---|---|---|
| ||
char const *src_file = /* ... */; char const *dest_file = /* ... */; if (rename(src_file, dest_file) != 0) { /* Handle Error */ } |
...
Wiki Markup |
---|
If the programmer's intent is to not remove anyan existing destination file, the POSIX {{access()}} function can be used to check for the existence of a file \[[Open Group 04|AA. C References#Open Group 04]\]. This compliant solution only renames the source file if the file destination file does not exist. |
...
On file systems where the program does not have sufficient permissions in the directory to view the file, access()
may return -1
even when the file exists. In such cases, rename()
would will also fail because the program lacks adequate permissions to perform the operation.
...
A programmer that wants an application to behave the same on any C99 implementation must first determine what behavior to implement.
Compliant Solution (Erase Existing
...
Destination File)
This compliant solution ensures that any destination file is portably removed.
...
The return value of remove()
is deliberately not checked, because it is expected to fail in the case where the file does not exist. If the file exists but cannot be removed, the rename()
call will also fail and the error will be detected at that point.
Compliant Solution (Protect Existing
...
Destination File)
This compliant solution only renames the source file if the destination file does not exist.
...