如何在 C++ 中使用 boost::iostreams 实时解压 GZ 文件
此最小示例展示如何在 C++ 中打开 .gz 文件,使用 boost::iostreams 实时解压,然后将其内容复制到 stdout:
iostreams_gz_decompress.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] << " <gzip 输入文件>" << endl;
}
//从第一个命令行参数读取,假设它是 gzip 压缩的
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);
//将 streambuf 转换为 istream
istream instream(&inbuf);
//将 instream 中的所有内容复制到
cout << instream.rdbuf();
//清理
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-decompress iostreams-gz-decompress.cpp)
target_link_libraries(iostreams-gz-decompress ${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