如何从zlib确定压缩后的数据的压缩大小? [英] How to determine compressed size from zlib for gzipped data?

查看:684
本文介绍了如何从zlib确定压缩后的数据的压缩大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用zlib执行gzip压缩. zlib压缩后将数据直接写到打开的TCP套接字中.

I'm using zlib to perform gzip compression. zlib writes the data directly to an open TCP socket after compressing it.

/* socket_fd is a file descriptor for an open TCP socket */
gzFile gzf = gzdopen(socket_fd, "wb");
int uncompressed_bytes_consumed = gzwrite(gzf, buffer, 1024);

(当然,所有错误处理都已删除)

(of course all error handling is removed)

问题是:如何确定向套接字写入了多少字节? zlib中的所有gz *函数都处理未压缩域中的字节数/偏移量,并告诉(搜索)不适用于套接字.

The question is: how do you determine how many bytes were written to the socket? All the gz* functions in zlib deal with byte counts/offsets in the uncompressed domain, and tell (seek) doesn't work for sockets.

zlib.h标头显示该库还可以选择在内存中读取和写入gzip流."写入缓冲区是可行的(然后我可以随后将缓冲区写入套接字),但是我看不到如何使用该接口.

The zlib.h header says "This library can optionally read and write gzip streams in memory as well." Writing to a buffer would work (then I can write the buffer to the socket subsequently), but I can't see how to do that with the interface.

推荐答案

zlib实际上可以将gzip格式的数据写入内存中的缓冲区.

zlib can, in fact, write gzip formatted data to a buffer in memory.

zlib常见问题解答条目表示zlib.h中的注释.在头文件中,对deflateInit2()的注释提到您应该(任意?)在第4个参数(windowBits)后加上16,以便使库使用gzip格式(而不是默认的"zlib")对deflate流进行格式化格式).

This zlib faq entry defers to comments in zlib.h. In the header file, the comment for deflateInit2() mentions that you should (arbitrarily?) add 16 to the 4th parameter (windowBits) in order to cause the library to format the deflate stream with the gzip format (instead of the default "zlib" format).

此代码可正确设置zlib状态,以将gzip编码为缓冲区:

This code gets the zlib state set up properly to encode gzip to a buffer:

#include <zlib.h>
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
int level = Z_DEFAULT_COMPRESSION;
int method = Z_DEFLATED;  /* mandatory */
int windowBits = 15 + 16; /* 15 is default as if deflateInit */
                          /* were used, add 16 to enable gzip format */
int memLevel = 8;         /* default */
int strategy = Z_DEFAULT_STRATEGY;
if(deflateInit2(&stream, level, method, windowBits, memLevel, strategy) != Z_OK)
{
    fprintf(stderr, "deflateInit failed\n");
    exit(EXIT_FAILURE);
}

/* now use the deflate function as usual to gzip compress */
/* from one buffer to another. */

我确认此过程将产生与gzopen/gzwrite/gzclose接口完全相同的二进制输出.

I confirmed that this procedure yields the exact same binary output as the gzopen/gzwrite/gzclose interface.

这篇关于如何从zlib确定压缩后的数据的压缩大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆