std::basic_fstream<unsigned char> 在 Linux 上不起作用



在Linux上调用basic_fstream<unsigned char>流上的read()函数时出错:

basic_fstream<unsigned char> fs;
basic_string<unsigned char> buf(1000, '');
fs.open( "/tmp/file.txt", ios::in | ios::binary);
fs.read( &buf[0], 1000);

我跟踪了它抛出的位置:在函数__check_facet(const _Facet* __f)中,它抛出__throw_bad_cast(),因为__f为NULL。__check_facet()依次从underflow()调用,_M_codecvt作为参数(为NULL并导致失败(。

系统的语言环境是UTF8,代码是用--std=c++14编译的。在Windows上可以正常工作。

它能以某种方式纠正吗?

不需要标准库为unsigned char提供facet或locale。标准流的设计仅考虑到char(和wchar_t(。

我建议使用标准的std::ifstream。您可以用它读取二进制数据,并将其存储到unsigned char缓冲区中。您应该考虑为该缓冲区使用标准的std::vector容器,而不是std::basic_string

试试这个:

ifstream fs("/tmp/file.txt", ios::binary);
vector<unsigned char> buf(1000);
fs.read( reinterpret_cast<char*>(&buf[0]), 1000);

这将在所有平台上同样有效。

最新更新