How to control boost::iostreams gzip compression level

In our previous post How to gzip-compress on-the-fly in C++ using boost::iostreams we showed how to create a gzip-compressing output stream using the boost::iostreams library.

This example shows how to control the compression rate of gzip_compressor:

Instead of constructing boost::iostreams::gzip_compressor() without arguments, use boost::iostreams::gzip_params(level) as the argument, where level (1..9) represents the compression level with 9 representing the highest compression level and 1 representing the lowest compression level. Higher levels of compression lead to reduced filesizes but are slower (i.e. consume more CPU time) during compression.

If filesize matters to you, I recommend choosing level 9 since compression even with the high level is extremely fast on modern computers.

Full example:

#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] << " <output .gz file>" << endl;
    //Read filename from the first command line argument
    ofstream file(argv[1], ios_base::out | ios_base::binary);
    boost::iostreams::filtering_streambuf<boost::iostreams::output> outbuf;
    //Convert streambuf to ostream
    ostream out(&outbuf);
    //Write some test data
    out << "This is a test text!\n";
    boost::iostreams::close(outbuf); // Don't forget this!
cmake_minimum_required(VERSION 3.0)
find_package(Boost 1.36.0 COMPONENTS iostreams)

add_executable(iostreams-gz-compress iostreams-gz-compress.cpp)
target_link_libraries(iostreams-gz-compress ${Boost_LIBRARIES})