我设法集成了boost Iostream API以读取压缩文件。我遵循了boost页面中的文档,到目前为止有以下代码:
std::stringstream outStr;
ifstream file("file.gz", ios_base::in | ios_base::binary);
try {
boost::iostreams::filtering_istreambuf in;
in.push(boost::iostreams::gzip_decompressor());
in.push(file);
boost::iostreams::copy(in, outStr);
}
catch(const boost::iostreams::gzip_error& exception) {
int error = exception.error();
if (error == boost::iostreams::gzip::zlib_error) {
//check for all error code
}
}
该代码可以正常工作(因此请忽略上面的任何错别字和错误:))。
最佳答案
1)是,上面的代码会将整个文件copy()
放入字符串缓冲区outStr
中。根据description of copy
2)从filtering_istreambuf
切换到filtering_istream
,std::getline()将起作用:
#include <iostream>
#include <fstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
int main()
{
std::ifstream file("file.gz", std::ios_base::in | std::ios_base::binary);
try {
boost::iostreams::filtering_istream in;
in.push(boost::iostreams::gzip_decompressor());
in.push(file);
for(std::string str; std::getline(in, str); )
{
std::cout << "Processed line " << str << '\n';
}
}
catch(const boost::iostreams::gzip_error& e) {
std::cout << e.what() << '\n';
}
}
(如果需要证明,可以在该循环中添加
std::cout << file.tellg() << '\n';
。它将以较大的块增加,但从一开始就不等于文件的长度)关于c++ - 如何使用Boost IOStreams的Gzip文件界面逐行读取?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6420620/