Date: Mon, 3 Nov 1997 17:39:10 -0800 (PST) Message-Id: <199711040139.RAA11038@adit.ap.net> Mime-Version: 1.0 Content-Type: text/plain; charset="us-ascii" To: Peter Palotas , djgpp AT delorie DOT com From: Nate Eldredge Subject: Re: Writing to a file from dtor doesn't work! Precedence: bulk At 03:53 11/3/1997 -0500, Peter Palotas wrote: >Take a look at the following tiny bit of code: > >#include >class A >{ >private: > FILE *fl; >public: > A(void) > { > fl = fopen("test.log", "wt"); > fprintf(fl, "In A constructor\n"); > } > > ~A(void) > { > fprintf(fl, "In A destructor\n"); > fclose(fl); > } >}; > >A a; > >int main(void) >{ > return 0; >} > >Okay, now everyone probably sees what this should do. It should write the >two lines "In A constructor" and "In A destructor" to the file "test.log" >(provided that it successfully can open the file, but since this is only a >test program, I don't bother checking that. > >Well, the problem is that if you declare an object of 'A' at global scope, >like I did in this example, nothing gets written in the destructor! i.e. >the file only contains one line; "In A constructor". > >Declaring 'a' (an object of 'A') inside main() however makes everything >work as it's supposed to. (Reopening the file in the destructor also works >fine, so it seems as if the file is closed before we reach the destructor >or something?) You got it. See below. > >Now is this a bug, or is it normal behaviour? Becuase it doesn't seem >normal to me, and I haven't found any documentation on it either, so any >help solving this would be appreciated. I found the cause, but I still don't know if it's a bug. In src/libc/ansi/stdlib/exit.c, __stdio_cleanup_hook is called before the destructors. You guessed it, __stdio_cleanup_hook flushes all streams, and closes all except stdin, stdout, and stderr (cin, cout, cerr for C++). If this is not what's Supposed To Happen, it should be easy to change, just move two lines of code. *Are* files Supposed to work in destructors? Nate Eldredge eldredge AT ap DOT net