ofstream class -- error-checking

P

pauldepstein

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
 
X

Xiaobin.Huang

if (!mystream){ cerr << ...}
this works well, means !mystream.good()
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().
 
P

pauldepstein

Xiaobin.Huang said:
this works well, means !mystream.good()

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top