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

前端 未结 2 1174
既然无缘
既然无缘 2020-12-06 17:59

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          


        
2条回答
  •  攒了一身酷
    2020-12-06 18:23

    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.

提交回复
热议问题