Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to check the return status of fclose() if I'm only reading a file?

Tags:

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;
}
like image 502
Joey Adams Avatar asked Jun 10 '11 04:06

Joey Adams


People also ask

What happens if I dont use Fclose?

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.

What is the return value of Fclose?

The fclose() function returns 0 on success. If fclose() fails, it returns the value EOF .

When we close the file using fclose () Buffer still remains in memory?

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.

Why is Fclose important?

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.


Video Answer


2 Answers

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.

like image 73
littleadv Avatar answered Oct 18 '22 15:10

littleadv


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.

like image 41
Billy Donahue Avatar answered Oct 18 '22 13:10

Billy Donahue