Why is it if we read a file with fread() and don't include fclose to close the same same file reference but still it works.
However if we forgot to include fclose after fwrite then it doesn't work.i.e. no writing on file reflects.
fread()
, as the name implies, reads data from a file. Logically, it can't return until it's either actually read the data (stored it in the buffer you provided) or reported an error. As soon as fread()
returns, you can use the data.
fwrite()
, on the other hand, can go through multiple layers of buffering, in the C runtime library, in the OS, and elsewhere. fwrite()
returns when it's processed your data and written it ... somewhere. There's no guarantee that it's actually written to the physical file until you either flush it (fflush(outfile);
) or close it (fclose(outfile);
). As soon as fwrite()
returns, you can do what you like with the data you passed to it (it's been copied), but that's all you can assume.
If your program terminates normally, it will implicitly close (and therefore flush) all open output files. If your program terminates abnormally, this may not happen.
(Actually, I think there are some cases where data may not physically arrive in the file even after fclose()
or fflush()
.)