Versions Compared

Key

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

Wiki Markup
The C99 {{fopen()}} function is used to open an existing file or create a new one \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\]. However, in C99, {{fopen()}} does not indicate if an existing file has been opened for writing or a new file has been created. This may lead to a program overwriting or accessing an unintended file.

...

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

/* initialize file_name */
errno_t res = fopen_s(&fp, file_name, "w");
if (res != 0) {
  /* Handle error */
}

Compliant Solution (fopen(), C1x)

The new C1x standard provides a new flag to address this problem. Section 7.21.5.3, paragraph 5 has the following:

Opening a file with exclusive mode ('x' as the last character in the mode argument) fails if the file already exists or cannot be created. Otherwise, the file is created with exclusive (also known as non-shared) access to the extent that the underlying system supports exclusive access.

Wiki Markup
This option is also provided by the GNU C library (\[[Loosemore 2007|AA. Bibliography#Loosemore 07]\]).

This compliant solution uses the x mode character to instruct fopen() to fail rather than open an existing functions.

Code Block
bgColor#ccccff
langc

char *file_name;

/* initialize file_name */

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

Use of this option allows for the easy remediation of legacy code.

Compliant Solution (open(), POSIX)

Wiki Markup
The {{open()}} function, as defined in the Open Group Base Specifications Issue 6 \[[Open Group 2004|AA. Bibliography#Open Group 04]\], 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.

...

For examples on how to check for the existence of a file without opening it, see recommendation FIO10-C. Take care when using the rename() function.

...

(

...

)

...

Wiki Markup
Section 12.3 of the GNU C Library says \[[Loosemore 2007|AA. Bibliography#Loosemore 07]\]

...

function

...

This compliant solution uses the x mode character to instruct fopen() to fail rather than open an existing functions.

Code Block
bgColor#ccccff
langc

char *file_name;

/* initialize file_name */

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

Use of this (nonportable) extension allows for the easy remediation of legacy code.

Compliant Solution (fdopen(), POSIX)

...