我创建了一个std::bitset<8> bits
等于00000000
1个字节的位集。我已将输出文件定义为,std::ofstream outfile("./compressed", std::ofstream::out | std::ofstream::binary)
但是当我编写bits
using时outfile << bits
,的内容outfile
变为00000000
但文件的大小为8个字节。(最后的每一位bits
占用文件中的1个字节)。有什么办法可以将字节真正写入文件吗?例如,如果我写,11010001
则应将其写为一个字节,并且文件大小应为1字节而不是8字节。我正在为霍夫曼编码器编写代码,但无法找到将编码后的字节写入输出压缩文件的方法。
问题是operator<<
文本编码方法,即使您已指定std::ofstream::binary
。您可以put
用来编写单个二进制字符或write
输出多个字符。请注意,您负责将数据转换为其char
表示形式。
std::bitset<8> bits = foo();
std::ofstream outfile("compressed", std::ofstream::out | std::ofstream::binary);
// In reality, your conversion code is probably more complicated than this
char repr = bits.to_ulong();
// Use scoped sentries to output with put/write
{
std::ofstream::sentry sentry(outfile);
if (sentry)
{
outfile.put(repr); // <- Option 1
outfile.write(&repr, sizeof repr); // <- Option 2
}
}
谢谢你的回答。我还有一个问题,我会接受你的回答。在这一行中,
char repr = bits.to_ulong();
您已经写了评论your conversion code is probably more complicated than this
。这是什么意思铸造
unsigned long
从返回to_ulong
到一个char
只会工作时,此位集使用8位或更少位。如果您使用更多的东西,事情将会变得更加复杂。好,知道了。谢谢!