std::ifstream::exceptions() raises exception!
-
Hello!
Let us consider something like that:
#include<fstream> int main() { std::ifstream File; File.setstate( std::istream::eofbit ); File.exceptions( std::istream::eofbit ); //Setting new exceptions mask – exception here! return EXIT_SUCCESS; }The problem is that at line 7 the exception of class
std::ios_base::failureis thrown!I have read here that setting new exception mask should call
clear(rdstate()): it should remove EOF flag. Also it is not documented that this function can itself raise exceptions!What is the correct behavio(u)r of the
std::ifstream::exceptions()function?
-
clear(state) does not clear flags that are set in its argument. The observed behaviour is correct.
-
And what is the result of calling
clear(rdstate())? Raising exception if( rdstate() & exceptions() ) != 0?Another question: how can I make a read loop that will read all bytes until EOF, and throw exception if file becomes inaccessible for reasons other than EOF?
I tried to remove
std::istream::eofbitfrom exceptions mask, but the exception is still thrown when the EOF is reached. It seems that the EOF sets some other flag, not only eofbit:std::ifstream File; File.exceptions( std::istream::failbit | std::istream::badbit ); //No eofbit here File.open(fileName.c_str(), std::ios_base::in | std::ios_base::binary); do { File.ignore(1); //Still raise exception when EOF is reached :( } while(!File.eof()); File.close();
-
I tried to compile and run your code, and I found that it worked perfectly well, and no exceptions are thrown.
However, I changed the filename to something that doesnt exist.
And that's where I got the exception.I suppose the file you want to open simply doesnt exist. Maybe you should check with
if (File)whether the file was really opened.