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.
is_open()returns true if a previous call toopen()succeeded and there has been no intervening call toclose(). In your example,open()is called from the constructor.fail()returns true iffailbitorbadbitis set inrdstate.failbitgenerally 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 thefailbitto be set right after opening a file.badbitis set when the stream is corrupt and the next operation will fail.