...
If the desired behavior is to ensure that any file referenced by dest_file
the destination file is not erased or overwritten, POSIX programmers must implement additional safeguards.
...
This code example is non-compliant because if dest_the destination file exists it is removed by rename()
.
...
Compliant Solution (POSIX)
Wiki Markup |
---|
If the programmer's intent of the programmer is to not remove theany fileexisting referenced by {{dest_file}} if it exists prior to calling {{rename()}}destination file, the POSIX {{access()}} function can be used to check for the existence of a file explicitly \[[Open Group 04|AA. C References#Open Group 04]\]. This compliant solution only renames the file referenced by {{src_file}}source file if the file referenced by {{dest_file}}destination file does not exist. |
Code Block | ||
---|---|---|
| ||
char const *src_file = /* ... */; char const *dest_file = /* ... */; if (access(dest_file, F_OK) != 0) { if (rename(src_file, dest_file) != 0) { /* Handle error condition */ } } else { /* Handle file-exists condition */ } |
...
Consequently, it is unnecessary to explicitly check for the existence of the file referenced by dest_destination file before calling rename()
.
Code Block | ||
---|---|---|
| ||
char const *src_file = /* ... */; char const *dest_file = /* ... */; if (rename(src_file, dest_file) != 0) { /* Handle Error */ } |
Erase Existing
...
Destination File
If the desired behavior is to ensure that any file referenced by dest_the destination file is erased by the rename()
operation, Windows programmers must write additional code.
...
On Windows systems, it is necessary to explicitly remove the file referenced by dest_destination file before calling rename()
, if you want the file to be overwritten and the rename()
operation to succeed.
...
Compliant Solution (POSIX)
On POSIX systems, if the file referenced by dest_destination file exists prior to calling rename()
, the file is automatically removed.
...
This compliant solution ensures that any file referenced by dest_destination file is portably removed.
Code Block | ||
---|---|---|
| ||
char const *src_file = /* ... */; char const *dest_file = /* ... */; (void)remove(dest_file); if (rename(src_file, dest_file) != 0) { /* Handle error condition */ } |
...
This compliant solution only renames the file referenced by src_source file if the file referenced by dest_destination file does not exist.
Code Block | ||
---|---|---|
| ||
char const *src_file = /* ... */; char const *dest_file = /* ... */; if (!file_exists(dest_file)) { if (rename(src_file, dest_file) != 0) { /* Handle error condition */ } } else { /* Handle file-exists condition */ } |
...