c++ - std::basic_ifstream 抛出 std::bad_cast

标签 c++ file-io c++11 io ifstream

我正在尝试使用以下代码从文件中读取数据。 (请注意,您需要在 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

关于c++ - std::basic_ifstream 抛出 std::bad_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17628207/

相关文章:

c++ - 删除期间的 CPP Vector 构造函数调用

c++ - 使用 std::conditional_variable 等待条件

c++ - 使用 std::ofstream 仅重写前 30 个字符的方法?

python - 如何打开文本文件中的包装线,重新格式化文本文件

c++ - 内联数组初始化

c++ - 什么是 move 语义?

c++ - 在多项目 Visual Studio 解决方案中以不同配置编译项目

c++ - 在 C++ 中赋予回调函数访问类数据成员的权限

c++ - 用于读取 double 的 istream 操纵器

c# - 获取相对于当前工作目录的路径?