我正在尝试使用std::basic_ofstream<std::uint8_t>
将一些二进制数据写入文件,但是它在__check_facet()处抛出了bad_cast
。我想我应该以{{1}}的语言环境来imbue()
,但我真的不知道该怎么做。
我的动机是我想将写入二进制数据(std :: uint8_t版本)的流运算符与写入文本数据(char)的运算符区分开。
当std::codecvt<std::uint8_t, char, std::mbstate_t>
调用write
时失败,并且它具有空指针,因此抛出__check_facet()
。
bad_cast
(gdb) l
45 template<typename _Facet>
46 inline const _Facet&
47 __check_facet(const _Facet* __f)
48 {
49 if (!__f)
50 __throw_bad_cast();
51 return *__f;
52 }
#0 std::__check_facet<std::codecvt<unsigned char, char, __mbstate_t> > (__f=0x0) at /usr/include/c++/7/bits/basic_ios.h:50
#1 0x000055555555a1c0 in std::basic_filebuf<unsigned char, std::char_traits<unsigned char> >::xsputn (this=0x7fffffffdc38, __s=0x7fffffffdc2f "*X\311uUUU", __n=1)
at /usr/include/c++/7/bits/fstream.tcc:731
#2 0x0000555555557301 in std::basic_streambuf<unsigned char, std::char_traits<unsigned char> >::sputn (this=0x7fffffffdc38, __s=0x7fffffffdc2f "*X\311uUUU", __n=1) at /usr/include/c++/7/streambuf:451
#3 0x000055555555693c in std::basic_ostream<unsigned char, std::char_traits<unsigned char> >::_M_write (this=0x7fffffffdc30, __s=0x7fffffffdc2f "*X\311uUUU", __n=1) at /usr/include/c++/7/ostream:313
#4 0x00005555555560b0 in std::basic_ostream<unsigned char, std::char_traits<unsigned char> >::write (this=0x7fffffffdc30, __s=0x7fffffffdc2f "*X\311uUUU", __n=1)
at /usr/include/c++/7/bits/ostream.tcc:196
#5 0x0000555555555cb1 in main () at test.cpp:7
该问题仅出现在具有g ++(当前使用7.3.0)的Linux上,在具有msvc的Windows上正常运行。
编辑:
最后,我想为二进制和文本输出实现单独的重载流运算符。像这样:
#include <fstream>
int main()
{
std::basic_ofstream<std::uint8_t> ofs("test.bin", std::ios_base::out | std::ios_base::binary);
std::uint8_t x = 42;
ofs.write(&x, 1);
ofs.close();
}
谢谢!