I am trying to read data from a file using below code. (Note that you need to enable C++11 features on GCC to make this compile.)
#include <fstream>
typedef unsigned char byte;
int main()
{
std::string filename = "test.cpp";
std::basic_ifstream<byte> in(filename, std::basic_ifstream<byte>::in | std::basic_ifstream<byte>::binary);
in.exceptions(std::ios::failbit | std::ios::badbit);
byte buf[5];
in.read(buf, 5);
return 0;
}
However, when reading data I get an exception:
terminate called after throwing an instance of 'std::bad_cast' what(): std::bad_cast
This happens when the in.read(buf, 5)
command is invoked.
I know that I can suppress this exception by not setting the exception mask I set but this does not fix the problem, it only masks it. Without an exception mask, the code keeps working but 0 characters are read.
Does anyone know why this exception is thrown? And how do I make it go away?