Search code examples
cfile-handlingmingw32

Does fopen return NULL pointer if file is already open?


I was assuming that fopen returns NULL pointer if file is already open. But it looks fopen does not return NULL in case file is already open in "w" mode. Below is the code that I used to try this and I do not get any errors. I tried with mingw32 as well as TDM-GCC-64 compilers. If I am not mistaken, C++ gives error if file is already open.

#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;
}

Edit: Added extra code to write some data to both fp1 and fp2 and see the behavior. If executed, file1.txt contains data BMS and seems to be correct behavior and fp1 and fp2 move independently as expected. First AMS is written using fp1 and then A is replaced by B using fp2 and final output is BMS.


Solution

  • According to the C Standard (7.19.3.8), it is implementation-defined:

    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.

    On top of that, it is discouraged for other reasons, see for instance 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).