c++ - boost gzip 解压缩字节数组

标签 c++ boost gzip zlib boost-iostreams

我实现了文件的 gzip/zlib 解压缩,如他们在 boost 站点上的示例所示。

void CompressionUtils::Inflate(std::ifstream& inputFile,
                               std::ofstream& outputFile)
{
   boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
   in.push(boost::iostreams::gzip_decompressor());
   in.push(inputFile);
   boost::iostreams::copy(in, outputFile);
}

这很好用。我还从套接字中读取数据,该套接字是从也被压缩的基于休息的 JSON 服务中获取的。我想我会写一个基于内存的实现,这有多难。好吧,我发现我不了解流和流缓冲区。我责怪过去几年的 Java ;) .. 所以我开始走这条路。

void CompressionUtils::Inflate(char* compressed, 
                               int size,
                               char* decompressed)
{

   boost::iostreams::stream<boost::iostreams::array_source> source(compressed,size);
   //std::stringstream str;

   boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
   in.push(boost::iostreams::gzip_decompressor());
   in.push(source);
   //boost::iostreams::copy(in, str);   
}

但我不知道我可以使用哪种流来基本上获得解压流的解压 char* 表示。这应该很容易,而且可能很容易,但我一直在浪费最后几个小时来进行不成功的尝试。

最佳答案

显然,您遇到了 filtering streams and stream buffers .您可以反向使用相同的方法将数据获取到字符串中。

我手边没有自己的示例,因此请将其视为某种伪代码,但这应该是您要查找的内容:

namespace io = boost::iostreams; //<-- good practice
typedef std::vector<char> buffer_t;

void CompressionUtils::Inflate(const buffer_t &compressed,
                               buffer_t &decompressed)
{
    io::filtering_ostream os;

    os.push(io::gzip_decompressor());
    os.push(io::back_inserter(decompressed));

    io::write(os, &compressed[0], compressed.size());
}

所以可以使用Boost提供的back inserter。

基本上,上面的代码所做的是定义一个您可以写入的输出流。它的设置是为了让所有写入其中的内容首先通过 gzip 解压缩,然后然后附加到 back_inserter 中,作为 back_inserters做,插入到解压缓冲区的后面。

此外,如您所见,缓冲区被包装在 std::vector 中。让我知道这是否适合您。

关于c++ - boost gzip 解压缩字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9119688/

相关文章:

c++ - boost::function 指向参数的函数指针?

c++ - 使用 Xcode 预编译 header 时 boost.log 中断

seo - Gzip/mod_deflate 如何影响爬虫/蜘蛛/机器人(最终也是我的 seo)?

mongodb - Golang-gzip将mongodb查找查询的游标数据,写入文件并将其解压缩时出错

c++ - CSV 解析器的性能瓶颈

c++ - 获取可执行文件路径

c++ - 为什么必须在何处以及为什么要放置"template"和"typename"关键字?

android - 为什么 GZip 算法的结果在 Android 和 .Net 中不一样?

c++ - 如何找到一个mac地址?

C++ std::priority_queue 使用 lambda 表达式