使用zlib将GZIP压缩到缓冲区中

时间:2018-04-03 05:36:18

标签: c linux gzip zlib content-encoding

我想使用 gzip 压缩内存缓冲区,并将压缩的字节放入另一个内存缓冲区。我想在带有Content-Encoding: gzip的HTTP数据包的有效负载中发送压缩缓冲区。我可以使用 zlib 轻松地进行deflate压缩(compress()函数)。但是,我没有看到我需要的API( gzip )。 zlib API用于压缩和写入文件(gzwrite())。但是,我想压缩并写入缓冲区。

有什么想法吗?

我在Linux上使用C语言。

3 个答案:

答案 0 :(得分:2)

不,zlib API确实在内存中提供了deflate函数的gzip压缩。您需要实际阅读zlib.h中的文档。

答案 1 :(得分:1)

Gzip是一种文件格式,这就是为什么看起来提供的实用程序功能在fd上运行的原因,使用shm_open()来创建具有足够内存的fd mmap()。重要的是写入的数据不会扩展映射区域的大小,否则写入将失败。这是mmapped区域的限制。

将fd传递给gzdopen()

但正如Mark在使用Basic API界面的回答中建议的那样,这是一种更好的方法。

答案 2 :(得分:1)

deflate()默认情况下以zlib格式工作,要启用gzip压缩,您需要使用deflateInit2()向windowBits“添加16”,如以下代码所示,windowBits是切换为gzip格式的关键

// hope this would help  
int compressToGzip(const char* input, int inputSize, char* output, int outputSize)
{
    z_stream zs;
    zs.zalloc = Z_NULL;
    zs.zfree = Z_NULL;
    zs.opaque = Z_NULL;
    zs.avail_in = (uInt)inputSize;
    zs.next_in = (Bytef *)input;
    zs.avail_out = (uInt)outputSize;
    zs.next_out = (Bytef *)output;

    // hard to believe they don't have a macro for gzip encoding, "Add 16" is the best thing zlib can do:
    // "Add 16 to windowBits to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper"
    deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 | 16, 8, Z_DEFAULT_STRATEGY);
    deflate(&zs, Z_FINISH);
    deflateEnd(&zs);
    return zs.total_out;
}

标题中的一些相关内容:

“该库可以选择读写gzip和原始deflate流   记忆。”

“在windowBits中添加16,以便在    压缩数据而不是zlib包装器”

这是deflateInit2()的有趣文档,距其定义有1000多行,除非必须,否则我不会再准备文档。

相关问题