使用boost将多个文件解压为一个文件

decompress multiple files in to one single file using boost

本文关键字:文件 一个 boost 使用      更新时间:2023-10-16

我有一组压缩文件。我必须解压缩所有文件并创建一个大文件。下面的代码工作得很好,但我不想使用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();

我知道有很多方法可以让Boost IOStreams知道它不应该关闭流。我想它要求你使用boost::iostream::stream<>而不是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