Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: fixed error checking

...

Code Block
bgColor#ffcccc
langc
#include <stdio.h>

void open_some_file(const char *file) {
  FILE *f = fopen(file, "r");
  if (NULL != f) {
    /* File exists, handle error */
  } else {
    if (fclose(f) != 0) {
      /* Handle error */
    }
    f = fopen(file, "w");
    if (NULL !== f) {
      /* Handle error */
    }
 
    /* Write to file */
    if (fclose(f) != 0) {
      /* Handle error */
    }
  }
}

Compliant Solution (

...

write)

This compliant solution uses only one instance of fopen(), and uses the x mode of fopen(), which was added in C11. This mode causes fopen() to fail if the file exists. This check and subsequent open is done performed without creating a race window. Note that the x mode provides exclusive access to the file only if the host environment provides this support.

Code Block
bgColor#ccccff
langc
#include <stdio.h>

void open_some_file(const char *file) {
  FILE *f = fopen(file, "wx")
  if (NULL !== f) {
    /* Handle error */
  }
  /* Write to file */
  if (fclose(f) != 0) {
    /* Handle error */
  }
}

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

void open_some_file(const char *file) {
  int fd = open(file, O_CREAT | O_EXCL | O_WRONLY);
  if (-1 != fd) {
    FILE *f = fdopen(fd, "w");
    if (NULL != f) {

      /* Write to file */

      if if (fclose(f) != 0) {
        /* Handle error */
      }
    }
    if (close(fd) != 0) {
      /* Handle error */
    }
  }
}

...