When I open a file in C, I am currently doing this:
int main()
{
FILE *f
f = fopen("employers.dat", "rb");
if(f == NULL)
{
PUTS("can not open the file:\"employers.dat\"");
fclose(f);
exit(-1);
}
return 0;
}
Is it necessary to use fclose
if the pointer is NULL
?
Is it necessary to use fclose if the pointer is NULL? Show activity on this post. Not only it is not necessary to use fclose () when f is NULL, but you should actually not invoke fclose () when f is NULL. If f is NULL, then the file was never opened to begin with, so it does not need any closing.
If the file is opened successfully fopen ( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
If an error occurs when the fopen () function is opening a file, it returns a null pointer. fopen () opens the file “try.c” in read mode. When a file is opened in read mode, three important tasks are performed by fopen ().
The macro NULL is defined in stdio.h as ’\0’. If a file is opened using the above method, fopen () detects any error in opening a file, such as a write-protected or a full disk, before attempting to write to it. A null is used to indicate failure because no file pointer will ever have that value.
Not only it is not necessary to use fclose()
when f
is NULL
, but you should actually not invoke fclose()
when f
is NULL
.
If f
is NULL
, then the file was never opened to begin with, so it does not need any closing.
Even if the file somehow needed closing, the solution could not possibly involve passing NULL
to fclose()
, because a NULL
parameter carries absolutely no information that fclose()
can use to figure out which file to close.
I am not sure whether fclose()
contains extra code for detecting and ignoring an erroneous NULL
parameter passed to it, but even if it does, it is best to not tempt your fate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With