Versions Compared

Key

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

The ISO/IEC 9899-1999 C standard function fopen() is typically used to open an existing file or create a new one. However, 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.

Non-Compliant Code Example 1

In this example, an attempt is made to check whether a file exists before opening it for writing by trying to open the file for reading.

Code Block
bgColor#FFCCCC
...
FILE *fp = fopen("foo.txt","r");
if( !fp ) { /* file does not exist */
  FILE *new_fp = fopen("foo.txt","w");
  ...
  fclose(new_fp);
} else {
   /* file exists */
  fclose(fp);
}
...

...