c++ - 如何在 C++ 中将字节写入文件?
问题描述
我创建了一个位集,使用std::bitset<8> bits
它相当于00000000
1 个字节。我将输出文件定义为,std::ofstream outfile("./compressed", std::ofstream::out | std::ofstream::binary)
但是当我编写bits
usingoutfile << bits
时,内容outfile
变为00000000
但文件大小为 8 个字节。(每个位bits
最终占用文件中的 1 个字节)。有没有办法真正将字节写入文件?例如,如果我写11010001
,那么这应该写为一个字节,文件大小应该是 1 个字节而不是 8 个字节。我正在为 Huffman 编码器编写代码,但我无法找到将编码字节写入输出压缩文件的方法。
解决方案
问题是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
}
}
推荐阅读
- python - 使用海龟 Python 测量距离
- javascript - 如何自定义 ace 编辑器自动完成功能?
- cmake - CMAKE_EXPORT_COMPILE_COMMANDS 不起作用,因为许多 cpp 文件以某种方式内置到 1 个大文件中
- reactjs - %public% 变量上的 npx create-react-app 后 index.html 中的警告(在 IntelliJ 中)
- c# - 新手 ASP.net MVC 导出到 Excel
- python - 用 BeautifulSoup 刮 Json 表太熊猫
- javascript - 有什么方法可以仅使用 Leaflet.js 获得类似“超级任天堂模式 7 上的 JRPG”的平面 3D 地图?
- linux-kernel - USB 设备驱动程序的字符设备接口
- pine-script - 退出策略以达到一定的效果
- flutter - @freezed copyWith 缺少密封类