其他分享
首页 > 其他分享> > c – std :: basic_ifstream抛出std :: bad_cast

c – std :: basic_ifstream抛出std :: bad_cast

作者:互联网

我试图使用下面的代码从文件中读取数据. (注意,您需要在GCC上启用C 11功能才能进行此编译.)

#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;
}

但是,在读取数据时,我得到一个例外:

terminate called after throwing an instance of 'std::bad_cast'
  what():  std::bad_cast

调用in.read(buf,5)命令时会发生这种情况.

我知道我可以通过不设置我设置的异常掩码来抑制此异常,但这不能解决问题,它只会掩盖它.如果没有异常掩码,代码将继续工作,但会读取0个字符.

有谁知道为什么抛出这个异常?我怎么让它消失?

解决方法:

c STL只包含char_traits的两个特化:

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

对于发布的代码,可以使用char_traits< byte>的定义是必须的.

更多细节在this SO question

标签:ifstream,c,c11,io,file-io
来源: https://codeday.me/bug/20190831/1777856.html