Related: fclose return value check
Although it's important to check the return value of fclose()
if you're writing a file (in case the flush operation fails), is it necessary to do so when reading a file?
FILE *f = fopen(path, "r");
if (f == NULL)
return 0;
/* Do something with the file... */
if (fclose(f) != 0) {
/* Error closing a file we successfully read. */
return 0;
}
As long as your program is running, if you keep opening files without closing them, the most likely result is that you will run out of file descriptors/handles available for your process, and attempting to open more files will fail eventually.
The fclose() function returns 0 on success. If fclose() fails, it returns the value EOF .
Closing a File The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file.
any file is i/o source, so similar to any source: after you worked with it, release it. fclose function is used for that reason, which allows a the file to be used by another manager/processer etc.
Is there anything you could do if it fails? Then yes. If there's nothing you can do - then you can ignore it.
Good practice is to always check for errors and at least log them, if there's nothing else you can do about it.
If the close() fails, you might have an error you care about. Files are more than data. They are metadata, and they are resources. If close() fails, you might still have a filehandle open. You might still be pinning the file's data, preventing it from being reused by the filesystem. You might still have network connections open. If the file's atime is updated on close(), you'll have a stale atime for the file. These are things you really should be curious about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With