繁体   English   中英

std::basic_fstream<unsigned char> 不适用于 Linux

[英]std::basic_fstream<unsigned char> doesn't work on Linux

basic_fstream<unsigned char>流上调用read()函数时,我在 Linux 上basic_fstream<unsigned char>

basic_fstream<unsigned char> fs;
basic_string<unsigned char> buf(1000, '\0');
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 并导致失败)。

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

可以以某种方式纠正吗?

标准库不需要为unsigned char提供方面或语言环境。 标准流的设计仅考虑了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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM