下面是使用 C 语言编写 zlib 库中 compress 算法的示例代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <zlib.h>
#define CHUNK 16384
int main(int argc, char *argv[]) { int ret, flush; unsigned have; z_stream strm; unsigned char in[CHUNK]; unsigned char out[CHUNK];
/* 初始化 zlib 结构体 */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = deflateInit(&strm, Z_DEFAULT_COMPRESSION);
if (ret != Z_OK)
return ret;
/* 读取输入数据并进行压缩 */
do {
strm.avail_in = fread(in, 1, CHUNK, stdin);
if (ferror(stdin)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
flush = feof(stdin) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = in;
/* 运行压缩算法 */
do {
strm.avail_out = CHUNK;
strm.next_out = out;