views:

64

answers:

2

Initialization 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.

+1  A: 

.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.

Goz
I edited my question to clarify the origin of the variable `file`. Thanks
NeDark
+2  A: 

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.

Brian Neal
Very precise. Thanks
NeDark