Mateusz Piotrowski
Mateusz Piotrowski

Reputation: 9157

Should I fclose(file) if an error occured?

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()?

Upvotes: 2

Views: 1252

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134386

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.

Upvotes: 5

Related Questions