如何在 C++ 中使用 boost::iostreams 实时 gzip 压缩
此最小示例展示如何在 C++ 中将数据写入 .gz 文件,使用 boost::iostreams 实时压缩数据。使用现代 iostreams 层,而不是像 zlib 这样的基于块的方法,允许你使用 std::ostream 的全部功能和易用性。
gzip_boost_iostreams.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());
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})If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow