1. 概述
- zlib :http://www.gzip.org/zlib/。
- zlib 是通用的压缩库,提供了一套 in-memory 压缩和解压函数,并能检测解压出来的数据的完整性(integrity)。zlib 也支持读写 gzip (.gz) 格式的文件。下面介绍两个最有用的函数——
compress
和uncompress
。
2. 压缩
int compress(unsigned char * dest, unsigned long * destLen, unsigned char * source, unsigned long sourceLen);
dest
:压缩后数据保存的目标缓冲区 destLen:目标缓冲区的大小(必须在调用前设置,并且它是一个指针)source
:要压缩的数据sourceLen
:要压缩的数据长度compress
()函数成功返回Z_OK
,如果内存不够,返回Z_MEM_ERROR
,如果目标缓冲区太小,返回Z_BUF_ERROR
int compress2 (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level);
level
: 相比上面compress
一个增加了压缩级别
3. 解压缩
int uncompress(unsigned char * dest, unsigned long * destLen, unsigned char * source, unsigned long sourceLen);
dest
:解压后数据保存的目标缓冲区 destLen:目标缓冲区的大小(必须在调用前设置,并且它是一个指针)source
:要解压的数据sourceLen
:要解压的数据长度uncompress()
函数成功返回Z_OK
,如果内存不够,返回*Z_MEM_ERROR*
,如果目标缓冲区太小,返回Z_BUF_ERROR
,如果要解压的数据损坏或不完整,返回Z_DATA_ERROR
。
4. 示例
- zlib 带的 example.c 是个很好的学习范例,值得一观。我们写个程序,验证 zlib 的压缩功能。所写的测试程序保存为 testzlib.cpp ,放在 zlib-1.1.4 目录下。程序源代码:
// testzlib.cpp 简单测试 zlib 的压缩功能
#include <cstring>
#include <cstdlib>
#include <iostream>
#include "zlib.h"
using namespace std;
int main()
{
int err;
Byte compr[200], uncompr[200]; // big enough
uLong comprLen, uncomprLen;
const char* hello = "12345678901234567890123456789012345678901234567890";
uLong len = strlen(hello) + 1;
comprLen = sizeof(compr) / sizeof(compr[0]);
err = compress(compr, &comprLen, (const Bytef*)hello, len);
if (err != Z_OK) {
cerr << "compess error: " << err << '\n';
exit(1);
}
cout << "orignal size: " << len
<< " , compressed size : " << comprLen << '\n';
strcpy((char*)uncompr, "garbage");
err = uncompress(uncompr, &uncomprLen, compr, comprLen);
if (err != Z_OK) {
cerr << "uncompess error: " << err << '\n';
exit(1);
}
cout << "orignal size: " << len
<< " , uncompressed size : " << uncomprLen << '\n';
if (strcmp((char*)uncompr, hello)) {
cerr << "BAD uncompress!!!\n";
exit(1);
} else {
cout << "uncompress() succeed: \n" << (char *)uncompr;
}
}
编译执行这个程序,输出应该是
D:\libpng\zlib-1.1.4>bcc32 testzlib.cpp zlib.lib
D:\libpng\zlib-1.1.4>testzlib
orignal size: 51 , compressed size : 22
orignal size: 51 , uncompressed size : 51
uncompress() succeed:
12345678901234567890123456789012345678901234567890