2

Code:

FILE *fp = fopen(filename, "r");
if (!fp)
{
    fprintf(stderr, "Failed to open a file\n");
    // fclose(fp) <-- should I close file here?
    exit(1);
}
// Some operations on the file.
fclose(fp);

Question:

If fopen() fails to open a file, should I still call fclose()?

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79

1 Answers1

5

No, you don't need to call fclose() inside if block. Once fopen() fails, it retruns NULL which need not be closed.

To elaborate, if fopen() is success, it will return a FILE *. That needs to be closed. FWIW, the returned pointer in this case, be of whatever value, gurantees to compare unequal with a NULL. In other words, if fopen() is a success, the returned pointer will always FAIL the if(!fp) check.

In error scenario (when the file cannot be opned for some reason), NULL will be retrurned. A NULL return value means, the file was not opened. You don't close what is not already opened. Simple.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261