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

前端 未结 2 1169
既然无缘
既然无缘 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.

    0 讨论(0)
  • 2020-12-06 18:27

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

    0 讨论(0)
提交回复
热议问题