Difference between file.is_open() and file.fail()
Ini开发者_如何转开发tialization of file
:
ifstream file("filename.txt");
What's is the difference between if ( file.is_open() )
and if (! file.fail() )
?
What Should I use to make sure if the file is ready for I/O ?
We assume that variable file
contains a object of a file stream.
is_open()
returns true if a previous call to open()
succeeded and there has been no intervening call to close()
. In your example, open()
is called from the constructor.
fail()
returns true if failbit
or badbit
is set in rdstate
.
failbit
generally means that a conversion failed. For example, you tried to read an integer, but the next character is a letter. The stream is ok; you could read a character next and it would succeed. You would not expect the failbit
to be set right after opening a file.
badbit
is set when the stream is corrupt and the next operation will fail.
.is_open tells you that the file is open and ready to be used. .fail is most likely used to indicate that a previous operation (eg a read) has failed.
精彩评论