14

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?

Jason
  • 542
  • 5
  • 24
Pablo Marino
  • 471
  • 1
  • 5
  • 12

2 Answers2

28

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.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • Related to closing a NULL file handler: http://stackoverflow.com/questions/16922871/why-glibcs-fclosenull-cause-segmentation-fault-instead-of-returning-error – vsoftco Sep 19 '15 at 23:38
  • 3
    fclose() an NULL pointer is undefined behavior, and common implementations simply crash the program if you do that. – nos Sep 20 '15 at 00:38
  • 1
    I think I have seen gcc implementations able to do that, but since it's not standard, yes, we should not rely on that – Jean-François Fabre Oct 26 '18 at 13:29
1

Since the file is not opened there is no need to close the file.

Pradheep
  • 3,553
  • 1
  • 27
  • 35
  • 2
    You can savely free(NULL) but I cannot find any documentation which says, it is safe to do that for fclose(NULL). – BitTickler Sep 19 '15 at 23:24
  • @BitTicker No it's not. `fclose(NULL)` is undefined behavior. But indeed I can't find a way to support that assertion either. – Iharob Al Asimi Sep 19 '15 at 23:32
  • 1
    MSVC documentation says *"If `stream` is `NULL`, the invalid parameter handler is invoked, as described in Parameter Validation. If execution is allowed to continue, `fclose` sets `errno` to `EINVAL` and returns `EOF`. It is recommended that the stream pointer always be checked prior to calling this function."* – Weather Vane Sep 19 '15 at 23:33
  • @WeatherVane Interesting, it might just be implementation defined. The standard says nothing about it. With *glibc* a program calling `fclose(NULL)` would usually cause a `SIGSEGV` signal. – Iharob Al Asimi Sep 19 '15 at 23:35