Search code examples
c++boostbzip2

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

Edit: I'll accept alternatives to boost.


Solution

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