someguy someguy -4 years ago 247
C++ Question

Decompress bzip2 byte array

How would I decompress a bzip2-compressed byte array using boost? I found an example here, but the input is a file hence the use of

. The documentation isn't very clear for me :(.

Edit: I'll accept alternatives to boost.

Answer Source

Here's my code using DEFLATE compression in the boost.iostreams library; I'm sure you can hook in the corresponding BZip2 compressor instead:

#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

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

  // Input

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

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

The bzip2 compressor is called bzip2_(de)compressor().

If you want a byte buffer rather than a file, use a string stream:

char mydata[N];
std::string mydatastr(mydata, N);
std::istringstream iss(mydatastr, std::ios::binary);
std::ostringstream oss(mydatastr, std::ios::binary);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download