fread not returning error on closed file in C

178 Views Asked by At

From my understanding fread should not be able to read a file after said file has been closed with fclose. However, when running this code

int main(int argc, char* argv[]){`

    File *fid;
    int test;
    char buf_read [5];
    
    fid = fopen("test.txt", "rb");
    fclose(fid);
    test = fread(buf_read, 1, 5, fid);
    fprintf(stdout, "%d \n", test);
}

it prints 5, when with my understanding of how fread works it should print 0 as fread should not be able to read from a closed file. is there some functionality with fread or fclose that I am missing here?

1

There are 1 best solutions below

2
On

From the fclose man page:

any further access (including another call to fclose()) to the stream results in undefined behavior.

You're invoking undefined behavior; anything can happen, including seemingly-correct behavior like you're experiencing.

The best thing you can do is set the stream (fid) to NULL immediately after calling fclose.