...
While the likelihood of access()
returning a false negative is lower than that of fopen()
, 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()
will also likely fail since the program does not have adequate permissions inside the directory.
Compliant Solution (Windows)
Wiki Markup |
---|
On Windows, [{{_access_s()}}|http://msdn.microsoft.com/en-us/library/a2xs1dts(VS.80).aspx] allows one to check for the existence of a file \[[MSDN|AA. C References#MSDN]\]. |
Code Block | ||
---|---|---|
| ||
char const *old = /* ... */;
char const *new = /* ... */;
if (_access_s(new,0) != 0) {
if (rename(old, new) != 0) {
/* Handle Error */
}
} else {
/* Handle Error */
}
|
This _access_s()
example shares many of the same problems as the POSIX access()
example above.
Risk Assessment
Calling rename()
has implementation-defined behavior when the new file name refers to an existing file. Incorrect use of rename()
can result in a file being unexpectedly overwritten or other unexpected behavior.
...
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.9.4.2, "The {{rename}} function"
\[[MSDN|AA. C References#MSDN]\] [{{_access_s, _waccess_s}}|http://msdn.microsoft.com/en-us/library/a2xs1dts(VS.80).aspx]
\[[Open Group 04|AA. C References#Open Group 04]\] [{{access()}}|http://www.opengroup.org/onlinepubs/009695399/functions/access.html] |
...