Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decompress bzip2 byte array

Tags:

c++

boost

bzip2

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 ifstream. The documentation isn't very clear for me :(.

Edit: I'll accept alternatives to boost.

like image 551
someguy Avatar asked Aug 17 '11 20:08

someguy


1 Answers

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
  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);

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);
like image 98
Kerrek SB Avatar answered Nov 13 '22 05:11

Kerrek SB