cfilefclose

Strange behavior using fclose


When testing the fclose function, the printf("File \"file2.bin\" inexistent!"); line is not reached. If the fclose(p_file2) line is removed, the message is shown.

#include <stdio.h>

int main()
{
    printf("Hello files");
    FILE *p_file1, *p_file2;
    p_file1 = fopen("file1.bin", "w+b");
    p_file2 = fopen("file2.bin", "r+b");
    if (p_file2 == NULL)
        printf("File \"file2.bin\" inexistent!");
    
    fclose(p_file1);
    fclose(p_file2);

    return 0;
}

Why does that happen?


Solution

  • 2 primary issues here. The first is that fclose(NULL) leads to undefined behavior, so there is really no point is speculating about the other point, but it is clearly a source of confusion. printf does not always write any data to the output stream. Instead, the data is buffered and the write may be deferred to a later call to printf or until the program exits (or a call to fwrite or fflush or other conditions). Since your program invoked fclose(NULL), bad things happen and the write that should have been deferred never happens, so you don't see the message.

    Try adding a call to fflush immediately after the printf.