Reputation: 1048
Lets say I have a code to compute the size of a file :
std::ifstream ifs(path, std::ifstream::ate | std::ifstream::binary);
unsigned int size = ifs.tellg();
ifs.close();
Most of the time in C++, where/when is it relevant to call ifs.good()
?
In my case, is it better after creating the stream or after calling tellg()
?
Then, if good()
returns false
, should I close the stream explicitly?
Upvotes: 6
Views: 3835
Reputation: 3495
Starting from the point that you never need to close explicity a stream, good()
is a function to:
Check whether state of stream is good
Returns true if none of the stream's error state flags (eofbit, failbit and badbit) is set.
You can call it to verify if something ism't going well and then verify the other bits to check what is wrong. For example :
End-of-File reached on input operation (eofbit)
Logical error on i/o operation (failbit)
Read/writing error on i/o operation (badbit)
However is not useful to call good to think on manual close of the stream.
In my case, is it better after creating the stream or after calling tellg()?
For my opinion in this case you don't need to call good()
, but if you want to call it, is better after tellg()
that can set some bit of failure in it's execution.
Upvotes: 1