The ISO/IEC 9899-1999 C specification provides standard functions to manipulate files that are designed to avoid the details of the underlying system. However, file manipulation and file operations are inherently tied to the operating system. Many of the common vulnerabilities associated with file operations exist because the ISO/IEC 9899-1999 C specification lacks facilities to adequately interact with files and the file system, making it impossible to specify the correct behavior.

A better way to interact with files, in terms of security, is to use functions designed for the native system. Many implementation specific functions offer a level of control over file objects that the ISO/IEC 9899-1999 C specification does not.

Additionally, there are well-known recommendations for dealing with common file operations securely that use non-standard functions. This recommendation opens those options up to implementers of this standard.

File Creation

The C99 standard function fopen() is typically used to open existing, and create new files. However, fopen() does not provide a way to test file existence potentially allowing a program to overwrite or access and unintended file.

Non-Compliant Example 1

...
FILE * fptr= fopen(file_name, "w");
if (!fptr) {
  /* Handle Error */
}
...
h2. Compliant Solution 1.
...
int fd = open(file_name, O_CREAT | O_EXCL | O_WR_ONLY);
if (fd == -1) {
  /* Handle Error */
}
...