Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If file pointer is null, do I have to use fclose()? (C)

Tags:

c

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?

like image 694
Pablo Marino Avatar asked Sep 19 '15 23:09

Pablo Marino


People also ask

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.

What does fopen () do in C++?

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.

Why does fopen () return a null pointer when opening a 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 ().

What does the macro NULL mean in C++?

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.


1 Answers

Not only it is not necessary to use fclose() when f is NULL, but you should actually not invoke fclose() when f is NULL.

  1. If f is NULL, then the file was never opened to begin with, so it does not need any closing.

  2. 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.

  3. 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.

like image 119
Mike Nakis Avatar answered Oct 29 '22 10:10

Mike Nakis