Kai-Uwe Bux <jk********@gmx.netwrote:
Daniel T. wrote:
>Roland Pibinger wrote:
>>On Tue, 14 Nov 2006 04:35:11 -0800, "Jim Langston" wrote:
"Roland Pibinger" wrote in message
>>>>After close() check the stream state. Otherwise you don't know
"when a file is finsihed".
Please explain this. After you call .close() don't we know that
the file is "finished"?
But when .close() fails?
Can .close() fail? I think not.
The standard seems to allow close to fail [27.8.1.3/6]:
basic_filebuf<charT,traits>* close();
Effects: If is_open() == false, returns a null pointer. If a put area
exists, calls overflow(EOF) to flush characters. If the last virtual
member function called on *this (between underflow, overflow, seekoff,
and seekpos) was overflow then calls a_codecvt.unshift (possibly several
times) to determine a termination sequence, inserts those characters and
calls overflow(EOF) again. Finally it closes the file (??as if?? by
calling std::fclose(file)). If any of the calls to overflow or
std::fclose fails then close fails.
Returns: this on success, a null pointer otherwise.
Postcondition: is_open() == false.
So is_open() will subsequently and invariantly return false if close()
fails. Also, if close() returns a null pointer, that doesn't necessarily
mean that it failed (after all, it returns NULL if is_open() was false
on entry.
Quite a pickle. close() can "fail" but there is no way to know if it
actually did fail unless one first queries "is_open()". Also, if it does
fail, we are left with no options because despite that failure
"is_open()" will still equal false, and thus subsequent calls to close()
will continue to return NULL.
So what is the robust way to close a file?
if ( file.is_open() ) {
if ( file.close() == 0 ) {
// what do we do here? [A]
}
}
I guess in [A] above, we could try to re-open the file, if that failed
then the file object becomes useless and we are done with it, if it
succeeds, we can try to close it again. Then we are stuck alternating
between opening the file and closing it again until such time as either
open fails, or close succeeds. A rather non-deterministic problem, the
program could get locked in a infinite loop.
if ( file.is_open() ) {
while ( file.close == 0 ) {
file.open();
if ( ! file.is_open() ) {
break;
}
}
}
Something like that? :-(
--
To send me email, put "sheltie" in the subject.