Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added section for C11 fopen("x") compliant solution.

...

Code Block
bgColor#FFCCCC
langc
char *file_name;
FILE *fp;

/* Initialize file_name */

fp = fopen(file_name, "w");
if (!fp) {
  /* Handle error */
}

Compliant Solution (fopen("x"), C11)

Starting in C11 a new mode suffix ("x") was added to the fopen() function which causes fopen() to return NULL if the file already exists or cannot be created [ISO/IEC 9899:2011].

Code Block
bgColor#ccccff
langc
char *file_name;
FILE *fp;

/* Initialize file_name */

fp = fopen(file_name, "wx");
if (!fp) {
  /* Handle error */
}

Compliant Solution (open(), POSIX)

The open() function, as defined in the Standard for Information Technology—Portable Operating System Interface (POSIX®), Base Specifications, Issue 7 [IEEE Std 1003.1:2013], is available on many platforms and provides finer control than fopen(). In particular, open() accepts the O_CREAT and O_EXCL flags. When used together, these flags instruct the open() function to fail if the file specified by file_name already exists.

...

Bibliography


...