On Mar 31, 9:52 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
BobR wrote:
[..]
Experts: Never ever tell someone they don't need to use .close() on a
file because it is going out-of-scope!! [..]
So, should I first define a default-constructed fstream and only then
.open() it?
That's a question of style. The important thing is that
regardless of whether you pass the filename directly to the
constructor, or call open explicitly, you check whether it has
succeeded. Similarly, the important thing is that after
actually closing the file, you check whether it succeeded or
not. Which, of course, you can't do if you close the file in
the destructor.j
There are some exceptions. For example, if you're processing an
error, which means that the contents of the file are invalid
anyway, and that the file will be immediately removed, it really
doesn't matter whether the flush in the close worked or not.
And the issue is usually much less critical for input; I don't
always bother closing input files explicitly.
I might add that if you're outputting to cout, you should flush
it and check the status before returning as well.
And in case the implementation I have is buggy, should I also work
around any potential problems by using only built-in types and
'if/else/goto' (in case there is a problem with 'switch/while/...'
or with user-defined types)? Just wondering...
What on earth for? Write errors are a fact of life, and can and
must be handled. Where as you really have to assume that your
implementation is working correctly; if e.g. main memory fails
(it's happened to me), there's not much a program can do about
it. (And of course, unlike write errors, it's pretty rare.)
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34