使用boost来压缩和解压缩gzip流

时间:2015-05-10 16:56:36

标签: c++ boost compression gzip

我想使用boost来(de)压缩gzip流(而不是文件),所以我写了这段代码:

#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <sstream>

int main(int argc, char** argv) {

   std::stringstream ss, comp, decomp;
   ss << "Hello World";

   boost::iostreams::filtering_streambuf< boost::iostreams::input> in;
   in.push(boost::iostreams::gzip_compressor());
   in.push(ss);
   boost::iostreams::copy(in, comp);

   std::cout << "Compressed: ";
   std::cout << comp.str() << std::endl;

   boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
   inbuf.push(boost::iostreams::gzip_decompressor());
   inbuf.push(comp);
   boost::iostreams::copy(inbuf, decomp);

   std::cout << "Decompressed: ";
   std::cout << decomp.str() << std::endl;
}

首先,压缩字符串,然后将其解压缩为原始字符串。这段代码编译得很好但是当我执行它时,压缩部分工作并打印其输出,但是对于解压缩部分,我得到这个错误:

terminate called after throwing an instance of'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::iostreams::gzip_error> >'
what():  gzip error
Aborted (core dumped)

那么请你告诉我我做错了什么?

更新

如果我将压缩器和解压缩器更改为bz2格式(使用bzip2_compressor和bzip2_decompressor方法),错误将会消失,它将正常工作。

0 个答案:

没有答案