2013-02-04 39 views
2

有人可以告诉我我需要使用哪个函数来解压缩使用vb.net的gzipstream压缩过的字节数组。我想用zlib。如何使用zlib解压gzipstream

我已经包含了zlib.h,但是我一直无法弄清楚我应该使用什么函数。

回答

6

您可以在The Boost Iostreams Library看一看:

#include <fstream> 
#include <boost/iostreams/filtering_stream.hpp> 
#include <boost/iostreams/filter/gzip.hpp> 

std::ifstream file; 
file.exceptions(std::ios::failbit | std::ios::badbit); 
file.open(filename, std::ios_base::in | std::ios_base::binary); 

boost::iostreams::filtering_stream<boost::iostreams::input> decompressor; 
decompressor.push(boost::iostreams::gzip_decompressor()); 
decompressor.push(file); 

再经行解压行:

for(std::string line; getline(decompressor, line);) { 
    // decompressed a line 
} 

或者整个文件到一个数组:

std::vector<char> data(
     std::istreambuf_iterator<char>(decompressor) 
    , std::istreambuf_iterator<char>() 
    ); 
+0

谢谢,我该怎么做,存储在字符数组中'char *' – Lotzki

+0

@Lotzki请参阅“或整个文件到数组中:”示例。 –

+0

@Lotzki如果你不确定'vector'是什么,请参阅http://en.cppreference.com/w/cpp/container/vector –

0

您需要使用inflateInit2()要求gzip的解码。阅读zlib.h中的文档。

zlib distribution中有很多示例代码。也看看this heavily documented example of zlib usage。您可以修改该号码以使用inflateInit2()而不是inflateInit()

+0

我一直在试图理解文档几个小时...我只是不'不了解它。在vb.net中,我花了10分钟,我不知道为什么我在这个问题上遇到了很多麻烦。 如何将'char *'转换为正确的流以调用'inflateInit2()'?我怎样才能得到输出为'char *'?没有任何简单的示例代码? – Lotzki

+0

你不需要转换任何东西。 –

0

这里是一个C函数,没有工作与zlib:和

int gzip_inflate(char *compr, int comprLen, char *uncompr, int uncomprLen) 
{ 
    int err; 
    z_stream d_stream; /* decompression stream */ 

    d_stream.zalloc = (alloc_func)0; 
    d_stream.zfree = (free_func)0; 
    d_stream.opaque = (voidpf)0; 

    d_stream.next_in = (unsigned char *)compr; 
    d_stream.avail_in = comprLen; 

    d_stream.next_out = (unsigned char *)uncompr; 
    d_stream.avail_out = uncomprLen; 

    err = inflateInit2(&d_stream, 16+MAX_WBITS); 
    if (err != Z_OK) return err; 

    while (err != Z_STREAM_END) err = inflate(&d_stream, Z_NO_FLUSH); 

    err = inflateEnd(&d_stream); 
    return err; 
} 

未压缩的字符串在uncompr返回。它是一个以空字符结尾的C字符串,因此您可以执行puts(uncompr)。上述功能仅适用于输出为文本的情况。我已经测试过它,它工作。