首页 > 解决方案 > 一点一点地写入文件

问题描述

我正在用 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++ 的方式不是很熟悉)

标签: c++bit-manipulationfstream

解决方案


推荐阅读