如何控制 boost::iostreams gzip 压缩级别

在我们的上一篇文章如何在 C++ 中使用 boost::iostreams 实时 gzip 压缩中,我们展示了如何使用 boost::iostreams 库创建 gzip 压缩输出流。

此示例展示如何控制 gzip_compressor 的压缩率:

不要构造不带参数的 boost::iostreams::gzip_compressor(),而是使用 boost::iostreams::gzip_params(level) 作为参数,其中 level(1..9)表示压缩级别,9 表示最高压缩级别,1 表示最低压缩级别。更高的压缩级别会减小文件大小,但在压缩过程中速度较慢(即消耗更多 CPU 时间)。

如果文件大小对你很重要,我建议选择级别 9,因为即使是高级别压缩在现代计算机上也极其快速。

#完整示例:

iostreams-gz-compress.cpp
#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 << "用法: " << argv[0] << " <输出 .gz 文件>" << endl;
    }
    //从第一个命令行参数读取文件名
    ofstream file(argv[1], ios_base::out | ios_base::binary);
    boost::iostreams::filtering_streambuf<boost::iostreams::output> outbuf;
    outbuf.push(boost::iostreams::gzip_compressor(
        boost::iostreams::gzip_params(9)
    ));
    outbuf.push(file);
    //将 streambuf 转换为 ostream
    ostream out(&outbuf);
    //写入一些测试数据
    out << "This is a test text!\n";
    //清理
    boost::iostreams::close(outbuf); // 不要忘记这个!
    file.close();
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
find_package(Boost 1.36.0 COMPONENTS iostreams)

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

Check out similar posts by category: C/C++