c++ - 一点一点地写入文件
问题描述
我正在用 C++ 实现熵编码模块。
该代码会生成一个 0 和 1 流,我想将其输出到文件中。
由于只能写入整个字节(?),因此需要一些缓存。我在想这样的事情:
struct out_cache_t {
uint8_t cache = 0;
uint8_t count = 0;
};
inline void cached_output(const int bit, out_cache_t &out_cache, std::ofstream &out) {
out_cache.cache <<= 1;
out_cache.cache |= bit;
out_cache.count += 1;
if (out_cache.count == 8) {
out.write((char*)&out_cache.cache, 1);
out_cache.count = 0;
}
}
void encode(...) {
out_cache_t out_cache;
std::ofstream out("output.txt");
// ... do encoding ...
if ( ... need to write 1 ... ) {
cached_output(1, out_cache, out);
} else if ( ... need to write 0 ... ) {
cached_output(0, out_cache, out);
}
// ... more stuff ...
}
但我想知道,标准库中是否有一些更简单或更有效的方法?在这种情况下,人们通常会做什么?
(请注意,我通常用 Python 编程,所以我对 C++ 的方式不是很熟悉)
解决方案
推荐阅读
- android-studio - Playstore 错误:App Bundle 包含本机代码,并且您尚未上传调试符号
- python - 如何更改散点图中的颜色密度?
- android - 在非常简单的 if 语句中获取错误运算符“!=”不能应用于“布尔”和“整数”
- android-studio - 在 Android Studio 中,如何查看函数调用链的中间值的类型是什么?
- json - 在 Cloudformation 中传递标签的 json 文件
- sql-server - 如何在 Azure DevOps 管道中将变量注入 SQL 脚本?
- azure-devops - 使用另一个项目的分支在 TFS 中创建一个全新的项目
- java - 如何在 Maven 构建过程中添加 Javac 选项?
- c# - 有没有办法找出谁在运行时试图加载给定的程序集?
- c++ - LNK1104:无法打开 libpjproject-i386-Win32-vc14-Debug-Static.lib