Functions that open additional (nontemporary) ﬁles require a file name, which is a string. The rules for composing valid ﬁle names are implementation-deﬁned. Whether the same file can be simultaneously open multiple times is also implementation-deﬁned.
Some implementations do not allow multiple copies of the same file to be open at the same time. Consequently, portable code cannot depend on what will happen if this rule is violated. Even on implementations that do not outright fail to open an already-opened file, a TOCTOU (time-of-check, time-of-use) race condition exists in which the second open could operate on a different file from the first due to the file being moved or deleted (see FIO45-C. Avoid TOCTOU race conditions while accessing files for more details on TOCTOU race conditions).
Noncompliant Code Example
This noncompliant code example logs the program's state at runtime:
Because the file
log is opened twice (once in
main() and again in
do_stuff()), this program has implementation-defined behavior.
In this compliant solution, a reference to the file pointer is passed as an argument to functions that need to perform operations on that file. This reference eliminates the need to open the same file multiple times.
Simultaneously opening a file multiple times can result in unexpected errors and nonportable behavior.
File system race condition
|LDRA tool suite|
|CERT_C-FIO24-a||Avoid race conditions while accessing files|
|CERT C: Rec. FIO24-C||Checks for situations where previously opened resources are reopened (rec. fully covered)|
|SEI CERT C Coding Standard||FIO45-C. Avoid TOCTOU race conditions while accessing files|
|SEI CERT C++ Coding Standard||VOID FIO21-CPP. Do not simultaneously open the same file multiple times|
|MITRE CWE||CWE-362, Concurrent Execution Using Shared Resource with Improper Synchronization ("Race Condition")|
CWE-675, Duplicate Operations on Resource
|[ISO/IEC 9899:2011]||Subclause 7.21.3, "Files"|