Versions Compared

Key

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

...

The mkstemp() algorithm for selecting file names has proven to be immune to attacks. This solution is not serially reusable, however, because the mkstemp() function replaces the "XXXXXX" in template the first it is invoked. This is not a problem, as long as template is reinitialized before calling mkstemp() a second time again. If template is not reinitialized, the mkstemp() function will do nothing because the template passed to it contains no return -1 and leave template unmodified because template did not contain six X's.

Code Block
bgColor#ccccff
char sfn[] = "temp-XXXXXX";
FILE *sfp;
int fd = mkstemp(sfn);
if (fd == -1) {
  /* Handle Error */
}

/* 
 * Unlink immediately to allow the name to be recycled.
 * The race condition here is inconsequential if the file
 * is created with exclusive permissions (glibc >= 2.0.7) 
 */

unlink(sfn);

sfp = fdopen(fd, "w+");
if (sfp == NULL) {
  close(fd);
  /* Handle Error */
}

/* use temporary file */

fclose(sfp); /* also closes fd */

...