The C fopen() function is used to open an existing file or create a new one [ISO/IEC 9899:2011]. However, in C, fopen() does not indicate whether 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.
...
Compliant Solution (fopen(), C11)
The C standard Standard provides a new flag to address this problem. Section 7.21.5.3, para. paragraph 5 [ISO/IEC 9899:2011], states:
...
This compliant solution uses the x mode character to instruct fopen() to fail rather than open an existing functionsfile.
| Code Block | ||||
|---|---|---|---|---|
| ||||
char *file_name;
/* initialize file_name */
FILE *fp = fopen(file_name, "wx");
if (!fp) {
/* Handle error */
}
|
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| CoverutyCoverity | 6.5 | OPEN_ARGS | Fully Implemented | ||||||
| PRQA QA-C |
| warncall for fopen and fopen_s | Partially implemented |
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...
...
| TR 24731-1:2007 | Section 6.5.2.1, "The fopen_s |
...
| Function" |
Bibliography
| [ISO/IEC 9899:2011] | Section 7.21.5.3, "The fopen Function" |
| [Loosemore 2007] | Section 12.3, "Opening |
...
| Streams" | |
| [Open Group 2004] | |
| [Seacord 2005a] | Chapter 7, "File I/O" |
...