22

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;
}
Community
  • 1
  • 1
Joey Adams
  • 41,996
  • 18
  • 86
  • 115
  • 2
    It depends on how important the data you are supposed to be reading is. If the `fclose()` fails, it is likely that there was a problem during the reading too - maybe because something trampled over the file stream structure. In which case, you may not have read all the data you were supposed to, and producing an answer based on part of the data could be a problem. Do many people write the code to do that check? No; a lot of people do not check that the close succeeds. However, that might be because the data being processed is not critical. – Jonathan Leffler Jun 10 '11 at 05:32
  • 1
    @Jonathan, if fread doesn't return errors, why would you assume there was an error just because of a failure of a different system call? I can't really imagine why a file opened for read would fail to close, but if it happens - I don't think you can assume that a previous call which didn't return a failure in fact failed. Doesn't make much sense to me. – littleadv Jun 10 '11 at 06:01
  • @littleadv: Did you check using `feof(fp)` vs `ferror(fp)` whether the read failed or reached EOF? I don't usually do that; I don't think I'm in a minority, either. You're right; if all the prior reads succeeded and you confirmed that you got EOF and not an error on the final read, then it is pretty unlikely that the `fclose()` will fail. It could happen, but it is not likely. And I mentioned the most likely reasons for `fclose()` to fail, namely memory trampling in some shape or form, or some mismanagement of the file pointer (not closing the file you actually had open). Definitely unlikely. – Jonathan Leffler Jun 10 '11 at 06:15

2 Answers2

11

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.

littleadv
  • 20,100
  • 2
  • 36
  • 50
1

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.

Billy Donahue
  • 564
  • 2
  • 10