On Tue, 23 Jan 2007 23:14:43 GMT, "Daniel T." wrote:
>rpbg123@...com (Roland Pibinger) wrote:
>Merely calling fclose() in the destructor is not the right solution
when the file has been opened for writing. You need to check the
return value of fclose() and conduct appropriate action when
fclose() fails.
Could you post some more details on this one? What kind of actions is
appropriate when fclose fails?
This is more a design than an implementation question. One common
setting is that the whole file is read into memory, some changes are
made and the contents is written back to disk by overwriting the
original file. When fwrite() or fclose() fails the original file is
already destroyed and the new file is corrupt (half written).
One solution is that the original file is never overwritten, i.e.
never opened for write. This means that you write the contents to a
temporary file, close the temporary file (check the return value),
delete the original file and rename the temporary file to the original
file. Error-/failure-handling in that case just means that the
partially written temporary file is closed and deleted (the original
file remians unchanged). This kind of error-/failure-handling can also
be done in the destructor when the file has not been closed before
(the destructor performs only error-/failure-handling).
>I ask because basic_fstream's close
function returns void. Presumably, it does the appropriate action you
speak of?
AFAIK, fstream() has functions like good(), bad(), fail(), ... to let
the user ckeck the stream state.
Best wishes,
Roland Pibinger