Fclose a file that is already fclose

后端 未结 1 1371
醉酒成梦
醉酒成梦 2020-12-19 08:10

In my programm I may close a file that is already close. What happen when I do a fclose on a file already close ?

And if you can\'t do so, how to know i

相关标签:
1条回答
  • 2020-12-19 08:31

    Calling fclose twice with the same stream is undefined behaviour - most likely crash. There is no way to check if FILE* has been closed already, so the safe solution is to set pointer to NULL as soon as it is closed:

    fclose(fh);
    fh = NULL;
    

    Sources: "The value of a pointer to a FILE object is indeterminate after the associated file is closed" (C draft standard). "After the call to fclose(), any use of stream causes undefined behaviour." (The Single UNIX ® Specification).

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