ango
ango

Reputation: 859

Is fclose needed when fopen has failed?

consider the below code snippet.

{
....
FILE *fptr = fopen("file_that_does_not_exist","r");
...
}

here, if fopen fails, do we still need to call fclose() for some cleanup ??

Upvotes: 14

Views: 7824

Answers (4)

Kartikya
Kartikya

Reputation: 453

Its simple friend, i mean just imagine.... Do you have to shutdown a computer even if it fails to boot up.... :D

Just the same way you don't need to close a file which you actually never opened.

Some extra tip : fclose is used just for the sake of freeing the file so that it could be used by some other application or module, as it is not a sharable resource. Also, fclose means you now free the pointer you were using and can use it for any other file.

Upvotes: 9

Bojan Komazec
Bojan Komazec

Reputation: 9526

No. You cannot close doors that are not opened. If succeeds, fopen returns pointer to the open file and only makes sense to pass this value to fclose.

Upvotes: 1

moatPylon
moatPylon

Reputation: 2191

No, since fopen() returns 0, which is an invalid file handle. fclose() may even crash if you try to do this.

Upvotes: 19

Daniel Daranas
Daniel Daranas

Reputation: 22624

No. It is not necessary. You didn't open anything in the first place, so you don't need to close it.

Upvotes: 2

Related Questions