C++:使用 boost::iostreams 迭代 GZ 文件中的行
问题:
你有一个 gzipped 文件,想用 C++ 解压缩。你不想使用管道在外部进程中 gzip。你也不想使用 zlib 和手动缓冲。
解决方案
这是官方 gzip_decompressor 示例的扩展。如果你使用正确的解压缩过滤器,它也适用于 bzip2 文件。
程序接受单个命令行参数(gzipped 文件)并将其解压缩输出打印到 stdout。
myzcat.cpp
/**
* myzcat.cpp
* zcat 替代品,用于教育目的。
* 使用 boost::iostream 和 zlib。
*
* 编译方式:
* clang++ -o myzcat myzcat.cpp -lz -lboost_iostreams
*
* 此代码作为公共领域发布。
*/
#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
int main(int argc, char** argv) {
if(argc < 2) {
std::cerr << "Usage: " << argv[0] << " <gzipped input file>" << std::endl;
}
//从第一个命令行参数读取,假设它是 gzipped
std::ifstream file(argv[1], std::ios_base::in | std::ios_base::binary);
boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
inbuf.push(boost::iostreams::gzip_decompressor());
inbuf.push(file);
//将 streambuf 转换为 istream
std::istream instream(&inbuf);
//迭代行
std::string line;
while(std::getline(instream, line)) {
std::cout << line << std::endl;
}
//清理
file.close();
}Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow