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

Evans Belloeil
  • 2,413
  • 7
  • 43
  • 76
  • Seems like a number of those results answer your question. – crashmstr Jul 03 '14 at 14:14
  • 2
    No ... But thanks for the down vote ... Can't ask a question on this site :( – Evans Belloeil Jul 03 '14 at 14:17
  • I looked through the results, and it seems like they answer your question as stated. [What happens to FILE pointer after file is closed?](http://stackoverflow.com/questions/8441059/what-happens-to-file-pointer-after-file-is-closed), [Double free error on fclose() on previously closed file handle](http://stackoverflow.com/questions/12811464/double-free-error-on-fclose-on-previously-closed-file-handle) – crashmstr Jul 03 '14 at 14:18
  • 2
    Try it and see... However: if `fopen` fails, the `FILE *` is set to `NULL`, that's how you can tell if a `FILE *` is set or not. Just set it to `NULL` after `fclose` if you want to play it extra-safe – Elias Van Ootegem Jul 03 '14 at 14:26
  • @crashmstr seems a little different to me - this asks what should happen when you call fclose twice - that question says "hey, my particular library implementation logs some crap I don't want" - which generally shouldn't be the case - and asks for a workaround. Of course, Evans might be unlucky enough to have the same implementation/problem, but that's not established. – Tony Delroy Jul 03 '14 at 14:29
  • 1
    Not clear why this was downvoted, I could not find an older duplcate of this question. – Shafik Yaghmour Apr 01 '15 at 20:22
  • @ShafikYaghmour This is the 1st result I found from Google also. Maybe it's fundamental knowledge to someone, but to me, it's totally valuable. – Lê Quang Duy Sep 05 '20 at 02:37

1 Answers1

20

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

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
  • The standard does not seem to apply to the case of a call to fclose with NULL, so it is an undefined behavior that can also lead to crash – אנונימי Dec 01 '21 at 10:38