如何使用 Boost IOStreams 的界面逐行读取 Gzip 文件?
How can I read line-by-line using Boost IOStreams' interface for Gzip files?
我设法集成了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
}
}
代码运行良好(所以请忽略上面的拼写错误和错误:)。
- 看起来上面的代码将读取完整的文件并在创建filtering_istreambuf时将其存储在内存中。从我的调查来看,这是真的吗?如果文件被读取到内存中,那么对于大文件来说,这段代码可能是一个问题(这就是我正在处理的问题)
- 我当前的代码使用gzgets API从zlib中逐行读取gzipped。有没有一种方法可以使用boost API进行逐行读取
1)是的,上面的代码会将整个文件copy()
放入字符串缓冲区outStr
。根据复印的描述
函数模板副本从给定的Source模型读取数据,并将其写入给定的Sink模型,直到到达流的末尾。
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';
。它会以相当大的块增加,但从一开始就不等于文件的长度)
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- C++ mmap 到"fast" 与 gzip 文件的读取耦合
- 可以提高iostream读取和压缩gzip文件的速度
- 是否有一个易于使用的,独立于平台的包,我们可以用它来读取&在c++下编写gzip流
- 通过使用指向igzstreams的指针的STL向量来读取gzip文件
- 如何使用 Boost IOStreams 的界面逐行读取 Gzip 文件?