解压缩bzip2字节数组

5
我该如何使用boost解压缩bzip2压缩的字节数组?我在这里找到了一个示例(链接),但输入是一个文件,因此使用了ifstream。对我来说,文档不是很清楚 :(。
编辑:我会接受boost的替代方案。
1个回答

7

这里是我的代码,使用了boost.iostreams库中的DEFLATE压缩技术;你也可以将对应的BZip2压缩技术整合到其中:

#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/filter/bzip2.hpp>   // <--- this one for you
#include <boost/iostreams/write.hpp>

  // Output

  std::ofstream datfile(filename, std::ios::binary);
  boost::iostreams::filtering_ostreambuf zdat;
  zdat.push(boost::iostreams::zlib_compressor());  // your compressor here
  zdat.push(datfile);

  boost::iostreams::write(zdat, BUFFER, BUFFER_SIZE);

  // Input

  std::ifstream datfile(filename, std::ios::binary);
  boost::iostreams::filtering_istreambuf zdat;
  zdat.push(boost::iostreams::zlib_decompressor());
  zdat.push(datfile);

  boost::iostreams::read(zdat, BUFFER, BUFFER_SIZE);
bzip2_(de)compressor()。 如果你想使用字节缓冲区而不是文件,请使用字符串流:
char mydata[N];
std::string mydatastr(mydata, N);
std::istringstream iss(mydatastr, std::ios::binary);
std::ostringstream oss(mydatastr, std::ios::binary);

1
我想从字节数组中解压缩,而不是像我链接的示例那样从文件中解压缩。另外,对于输出,您放置了zlib_decompressor(),并且在输入中将“zidx”传递给读取函数,而应该是“zdat”。 - someguy
抱歉,那是一个打字错误。对于字节数组,只需使用字符串流而不是从字节数组构造的字符串构造的文件流即可。我会添加这个建议。 - Kerrek SB
如果我使用字符串,那么字节会被复制吗?我想要更高效的方法。如果不能使用boost完成这个任务,我会编辑问题并接受其他方案。 - someguy
@ildjarn:太棒了,我不知道这个。我会加上的! - Kerrek SB
@KerrekSB:没错,这一切都是实现定义的,而我所期望的工作方式只是在当时恰好在MSVC上运行。关于它让我困惑的问题在一段时间前得到了澄清,这是由Dietmar Kühl的这个答案引起的。然后我去纠正了我所有相关的答案(例如这个),但我没有想到要更正其他答案的评论... ;-] - ildjarn
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接