新博客地址: vonsdite.cn
1. 概述
- zlib :http://www.gzip.org/zlib/。
- zlib 是通用的壓縮庫,提供了一套 in-memory 壓縮和解壓函數,並能檢測解壓出來的數據的完整性(integrity)。zlib 也支持讀寫 gzip (.gz) 格式的文件。下面介紹兩個最有用的函數——
compress
和uncompress
。
- 壓縮
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
一個增加了壓縮級別
- 解壓縮
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