...
This creates issues when trying to write portable code , or when trying to implement alternative behavior.
...
Wiki Markup |
---|
If the programmer's intent is to not remove an 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 only if the destination file does not exist. |
...
This code contains an unavoidable race condition between the call to access()
and the call to rename()
and can consequently only be safely executed only within a secure directory (see FIO15-C. Ensure that file operations are performed in a secure directory).
...
Code Block | ||
---|---|---|
| ||
const char *src_file = /* ... */; const char *dest_file = /* ... */; if (rename(src_file, dest_file) != 0) { /* Handle Errorerror */ } |
Compliant Solution (Windows)
On Windows systems, it is necessary to explicitly remove the destination file before calling rename()
, if you want the file to be overwritten and the rename()
operation to succeed.
...
This code contains unavoidable race conditions between the calls to _access_s()
, remove()
and rename()
and can consequently only be safely executed only within a secure directory (see FIO15-C. Ensure that file operations are performed in a secure directory).
...
Portable Behavior
A programmer that who wants an application to behave the same on any C99 implementation must first determine what behavior to implement.
...
This code contains an unavoidable race condition between the call to remove()
and the call to rename()
and consequently can only be safely executed only within a secure directory (see FIO15-C. Ensure that file operations are performed in a secure directory).
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. This is a valid exception (EXP12-EX1) to recommendation EXP12-C. Do not ignore values returned by functions.
Compliant Solution (Preserve Existing Destination File)
This compliant solution only renames the source file only if the destination file does not exist.
...
This code contains an unavoidable race condition between the call to file_exists()
and the call to rename()
and can consequently only be safely executed only within a secure directory (see FIO15-C. Ensure that file operations are performed in a secure directory).
The file_exists()
function is provided by the application , and is not shown here as because it must be implemented differently on different platforms. (On POSIX systems it would use access()
, on Windows _access_s()
, and on other platforms whatever function is available to test file existence.)
...