【问题标题】:decompress multiple files in to one single file using boost使用 boost 将多个文件解压缩为一个文件
【发布时间】:2016-08-16 09:47:29
【问题描述】:

我有一组压缩文件。我必须解压缩所有文件并创建一个大文件。下面的代码工作正常,但我不想使用 std::stringstream 因为文件很大,我不想创建文件内容的中间副本。

如果我尝试直接使用boost::iostreams::copy(inbuf, tempfile);,它会自动关闭文件(tmpfile)。有没有更好的方法来复制内容?或者至少,我可以避免自动关闭这个文件吗?

std::ofstream tempfile("/tmp/extmpfile", std::ios::binary);
for (set<std::string>::iterator it = files.begin(); it != files.end(); ++it)
{
    string filename(*it);
    std::ifstream gzfile(filename.c_str(), std::ios::binary);

    boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
    inbuf.push(boost::iostreams::gzip_decompressor());
    inbuf.push(gzfile);

    //closes tempfile automatically!!
    //boost::iostreams::copy(inbuf, tempfile); 

    std::stringstream out;
    boost::iostreams::copy(inbuf, out);
    tempfile << out.str();
}
tempfile.close();

【问题讨论】:

  • 在目标文件上使用普通的输出过滤器?

标签: c++ boost gzip boost-iostreams


【解决方案1】:

我知道有一些方法可以让 Boost IOStreams 知道它不应该关闭流。我想它需要你使用boost::iostream::stream&lt;&gt; 而不是std::ostream

我看似可行的简单解决方法是使用与单个 std::filebuf 对象关联的临时 std::ostream

#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <set>
#include <string>
#include <iostream>
#include <fstream>

int main() {
    std::filebuf tempfilebuf;
    tempfilebuf.open("/tmp/extmpfile", std::ios::binary|std::ios::out);

    std::set<std::string> files { "a.gz", "b.gz" };
    for (std::set<std::string>::iterator it = files.begin(); it != files.end(); ++it)
    {
        std::string filename(*it);
        std::ifstream gzfile(filename.c_str(), std::ios::binary);

        boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
        inbuf.push(boost::iostreams::gzip_decompressor());
        inbuf.push(gzfile);

        std::ostream tempfile(&tempfilebuf);
        boost::iostreams::copy(inbuf, tempfile); 
    }
    tempfilebuf.close();
}

Live On Coliru

像样例数据

echo a > a
echo b > b
gzip a b

生成extmpfile 包含

a
b

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-10
    • 2015-07-09
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多