我设法集成了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
    }
}

该代码可以正常工作(因此请忽略上面的任何错别字和错误:))。
  • 看起来上面的代码将在创建filter_istreambuf时读取完整的文件并将其存储在内存中。从我的调查来看,这是真的吗?如果将文件读入内存,则此代码可能是大文件的问题(这是我要处理的问题)。
  • 我当前的代码逐行从zlib使用gzgets API读取gzip。有没有一种方法可以使用Boost API逐行读取?
  • 最佳答案

    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/

    10-11 22:38
    查看更多