5

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?

Chris
  • 6,914
  • 5
  • 54
  • 80
  • For me, it doesn't even compile: `no matching constructor for initialization of 'std::basic_ifstream` โ€“  Jul 13 '13 at 08:00
  • 2
    @H2CO3 As stated in the introduction, you need to enable C++11. Otherwise the constructor for the `basic_ifstream` does not exist. Alternative fix: use `filename.c_str()` instead of `filename`. โ€“ Chris Jul 13 '13 at 08:08
  • 1
    This problem has been solved here: http://stackoverflow.com/q/19205531/331024 It has a full implementation of char_traits and codecvt โ€“ x-x Oct 10 '13 at 22:27

2 Answers2

5

c++ STL only contains two specializations of char_traits:

   struct char_traits < char >;
   struct char_traits <wchar_t >;

For the code posted to work a definition of char_traits<byte> is required.

More details in this SO question

Community
  • 1
  • 1
suspectus
  • 16,548
  • 8
  • 49
  • 57
3

If you redefine byte as char the bad_cast exception will no longer occur.

I presume the basic_ifstream template is not fully debugged for unsigned char specialization. According to the Standard ยง 27.3, char_traits<CharType> need only be instantiated by the library for CharType = {char|char16_t|char32_t|wchar_t}

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182