【问题标题】:std::basic_fstream<unsigned char> doesn't work on Linuxstd::basic_fstream<unsigned char> 在 Linux 上不起作用
【发布时间】:2021-09-08 13:55:08
【问题描述】:

当在basic_fstream&lt;unsigned char&gt; 流上调用read() 函数时,我在Linux 上遇到了错误:

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。依次从underflow() 调用__check_facet(),以_M_codecvt 作为参数(为NULL 并导致失败)。

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

可以改正吗?

【问题讨论】:

  • C++ 库没有为无符号字符流提供 localte/facets。 C++ 规范不需要 C++ 库来执行此操作。 - this thread 可能会带来一些清晰性。
  • rawrex,感谢您的链接。也就是说,基本上,唯一的解决方案是使用标准的 std::fstream?
  • this的可能重复
  • @AlBerger 我喜欢 @Emile Cormier 在该线程的 cmets 中提出的“您自己的“二进制流”类”的想法。
  • @AlBerger 发布

标签: c++ linux


【解决方案1】:

标准库不需要为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);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多