Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 if a file is closed or open ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
484 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...