By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,512 Members | 1,814 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,512 IT Pros & Developers. It's quick & easy.

ofstream class -- error-checking

P: n/a
How should I check that a stream (for example a .txt file or the screen
-- std::cout ) is open and ready to receive input.

To declare the stream as an instantiation of the ofstream class,
I write

ofstream mystream("filename");

// Then, to check the stream is ready, should I say

if (!mystream){ cerr << ...}

// or should I say

if (mystream.bad()) {cerr << ...}

What are the pros and cons of both methods (if they both work)?

Thank you very much for your help.
Paul Epstein

Oct 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
>> if (!mystream){ cerr << ...}
this works well, means !mystream.good()
if (mystream.bad()) { cerr << ... }

means the stream has broken already

stream has four status:
bool good() const; //the next operate should be success
bool eof() const; //end of file
bool fail() const; //the next operate should be failed
bool bad() const; //baddly, the stream has broken

the deffrence between fail() and bad() is, if one stream gets to fail()
but not in bad() status the same time, we can assume the stream can
work. If one stream gets to bad(), all are over.

The operator ! returns fail().

Oct 23 '05 #2

P: n/a

Xiaobin.Huang wrote:
if (!mystream){ cerr << ...} this works well, means !mystream.good()
if (mystream.bad()) { cerr << ... }

means the stream has broken already

stream has four status:
bool good() const; //the next operate should be success
bool eof() const; //end of file
bool fail() const; //the next operate should be failed
bool bad() const; //baddly, the stream has broken

the deffrence between fail() and bad() is, if one stream gets to fail()
but not in bad() status the same time, we can assume the stream can
work. If one stream gets to bad(), all are over.

The operator ! returns fail().

Very helpful!

Thank you,

Paul

Oct 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.