When exactly to check std::ifstream::good()?
Asked Answered
A

1

6

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?

Agnes answered 31/1, 2020 at 11:1 Comment(2)
"should I close the stream explicitly?" - you never have to do that. std::fstream class is well mannered and it cleans up after itself.Raseta
You almost never use either good (the implicit conversion to bool is logically equivalent) or close explicitly. I haven't used either in years.Ask
I
1

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.

Inglebert answered 31/1, 2020 at 11:15 Comment(1)
I know what good() does. What I want to know is how it is commonly used by others, if it is relevant to use it, etc ... Maybe it is overkill to use it after each stream operation afterall, but I need advice here.Agnes

© 2022 - 2024 — McMap. All rights reserved.