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?
From the
fclose
man page: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
) toNULL
immediately after callingfclose
.