如果文件已经打开,fopen return 是否为 NULL 指针?

Does fopen return NULL pointer if file is already open?

如果文件已经打开,我假设 fopen returns NULL 指针。但它看起来 fopen 不会 return NULL 以防文件已经在 "w" 模式下打开。下面是我用来尝试这个的代码,我没有收到任何错误。我尝试使用 mingw32 和 TDM-GCC-64 编译器。如果我没记错的话,如果文件已经打开,C++ 会报错。

#include<stdio.h>

int main()
{
    FILE *fp1, *fp2;
    
    fp1 = fopen("file1.txt", "w");
    fp2 = fopen("file1.txt", "w");
    
    if(fp2 == NULL)
    {
        printf("Error in opening file\n");
        return(0);
    }
    
    // Edit: added following code to check the behavior if write operation
    // is performed simultaneously
    
    fputc('A', fp1);
    fputc('M', fp1);
    fputc('S', fp1);
    fputc('B', fp2);
    
    fclose(fp1);
    fclose(fp2);
    
    return 0;
}

编辑:添加了额外代码以将一些数据写入 fp1fp2 并查看行为。如果执行,file1.txt 包含数据 BMS 并且似乎是正确的行为,并且 fp1fp2 按预期独立移动。首先 AMS 使用 fp1 编写,然后 A 使用 fp2 替换为 B,最终输出为 BMS.

根据 C 标准 (7.19.3.8),它是实现定义的:

Functions that open additional (nontemporary) files require a file name, which is a string. The rules for composing valid file names are implementation-defined. Whether the same file can be simultaneously open multiple times is also implementation-defined.

最重要的是,由于其他原因不鼓励,例如 SEI CERT C Coding Standard's FIO24-C recommendation:

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).