Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Wiki Markup
A somewhat better solution involves using the POSIX {{access()}} function which can check for the existence of a file explicitly \[[Open Group 04|AA. C References#Open Group 04]\]. As with the {{fopen()}} solution, this code contains an unavoidable race condition and consequently can only be safely executed within a secure directory.  In fact the existence check is not really needed on POSIX systems, because POSIX specifies the behavior of {{rename()}} when the file referenced by {{new}} exists.

Code Block
bgColor#ccccff
char const *old = /* ... */;
char const *new = /* ... */;

if (access(new,F_OK) != 0) {
  if (rename(old, new) != 0) {
    /* Handle Error */
  }
} else {
  /* Handle Error */
}

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.

...

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]\]. As with the {{fopen()}} solution, this code contains an unavoidable race condition and consequently can only be safely executed within a secure directory.

Code Block
bgColor#ccccff
char const *old = /* ... */;
char const *new = /* ... */;

if (_access_s(new,0) != 0) {
  if (rename(old, new) != 0) {
    /* Handle Error */
  }
} else {
  /* Handle Error */
}

...