如何从 zlib 确定 gzip 数据的压缩大小?
我正在使用 zlib 执行 gzip 压缩。 zlib 将数据压缩后直接写入打开的 TCP 套接字。
/* 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);
(当然所有错误处理都被删除)
问题是:如何确定有多少字节写入了套接字? zlib 中的所有 gz* 函数都处理未压缩域中的字节计数/偏移量,并且tell(seek)不适用于套接字。
zlib.h 标头显示“该库也可以选择在内存中读取和写入 gzip 流。”写入缓冲区是可行的(然后我可以随后将缓冲区写入套接字),但我不知道如何使用接口来做到这一点。
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)
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过
deflate*
系列调用来完成此操作。我不会向您展示所有内容,但这个示例程序(我在目录中将其命名为“test.c”)应该可以帮助您入门:查阅
zlib 中的
。deflate
文档.hYou'll be able to do this with the
deflate*
series of calls. I'm not going to show you everything, but this example program (which I had named "test.c" in my directory) should help you get started:Consult the
deflate
documentation fromzlib.h
.事实上,zlib 可以将 gzip 格式的数据写入内存中的缓冲区。
此 zlib faq 条目遵循 zlib.h 中的注释。在头文件中, deflateInit2() 的注释提到您应该(任意?)将 16 添加到第四个参数(windowBits),以便使库使用 gzip 格式(而不是默认的“zlib”)格式化 deflate 流“ 格式)。
此代码正确设置了 zlib 状态,以将 gzip 编码到缓冲区:
我确认此过程产生与 gzopen/gzwrite/gzclose 接口完全相同的二进制输出。
zlib can, in fact, write gzip formatted data to a buffer in memory.
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).
This code gets the zlib state set up properly to encode gzip to a buffer:
I confirmed that this procedure yields the exact same binary output as the gzopen/gzwrite/gzclose interface.