The rename() function has the following prototype.:
| Code Block |
|---|
int rename(char const *old_file, char const *new_file); |
...
This code example is non-compliant because if new_file exists it will be is removed by rename().
| Code Block | ||
|---|---|---|
| ||
char const *old_file = /* ... */;
char const *new_file = /* ... */;
if (rename(old_file, new_file) != 0) {
/* Handle Error */
}
|
...
| Code Block | ||
|---|---|---|
| ||
char const *old_file = /* ... */;
char const *new_file = /* ... */;
(void) remove(new_file);
if (rename(old_file, new_file) != 0) {
/* Handle error condition */
}
|
This code contains an unavoidable race condition between the call to remove() and the call to rename() and consequently can consequently only be safely executed within a secure directory (see FIO17-A. 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 it needs to 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.)
...