How to decompress GZ files on-the-fly in C++ using boost::iostreams
This minimal example shows you how to open a .gz
file in C++, decompress it on-the-fly using boost::iostreams
and then copy its contents to stdout
:
#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
using namespace std;
int main(int argc, char** argv) {
if(argc < 2) {
cerr << "Usage: " << argv[0] << " <gzipped input file>" << endl;
}
//Read from the first command line argument, assume it's gzipped
ifstream file(argv[1], ios_base::in | ios_base::binary);
boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
inbuf.push(boost::iostreams::gzip_decompressor());
inbuf.push(file);
//Convert streambuf to istream
istream instream(&inbuf);
//Copy everything from instream to
cout << instream.rdbuf();
//Cleanup
file.close();
}
cmake_minimum_required(VERSION 3.0)
find_package(Boost 1.36.0 COMPONENTS iostreams)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(iostreams-gz-decompress iostreams-gz-decompress.cpp)
target_link_libraries(iostreams-gz-decompress ${Boost_LIBRARIES})