zlib庫函數的使用
1、int compress(Bytef *dest, uLongf *destLen, const Bytef* source, uLong sourceLen);
compress函數將source緩衝區的內容壓縮到dest壓縮區。sourceLen表示source緩衝區的大小(以字節計)。
destLen是傳址調用,當調用函數的時候,destLen表示dest緩衝區的大小 destLen>(sourceLen + 12)*100.1%
或者使用compressBound(sourceLen),當函數退出,destLen表示壓縮後緩衝區的實際大小
compress 若成功,返回Z_OK,若沒有足夠內存,返回Z_MEM_ERROR,若緩衝區不夠大,則返回Z_BUF_ERROR
2、int uncompress(Bytef *dest ,uLongf *destLen, const Bytef*source, uLong sourceLen);
uncompress函數將source緩衝區的內容解壓縮到dest緩衝區。sourceLen是source緩衝區的大小,destLen是傳址調用,dest緩衝區必須足以容下解壓後的數據,函數退出後,destLen是解壓後的數據的實際大小
uncompress若成功,則返回Z_OK,若沒有足夠內存,則返回Z_MEM_ERROR,若輸出緩衝區不夠,則Z_BUF_ERROR,若輸入數據有誤,則返回Z_DATA_ERROR
#include "zconf.h"
#include "zlib.h"
#include <iostream>
using namespace std;
#pragma comment(lib,"zdll.lib")
int main()
{
int err;
Byte compr[200],uncompr[200];
uLong comprLen,uncomprLen;
const char* hello = "1213135454646544665456465465457877874655312333131";
uLong len = strlen(hello)+1;
comprLen = sizeof(compr)/sizeof(compr[0]);
err = compress(compr,&comprLen,(const Bytef*)hello,len);
if(err != Z_OK){
cerr<<"compress error: "<<err<<endl;
exit(1);
}
cout<<"original size: "<<len<<" ,compressed size: "<<comprLen<<endl;
strcpy((char*)uncompr,"garbage");
err = uncompress(uncompr,&uncomprLen,compr,comprLen);
if(err != Z_OK){
cerr<<"uncompress error: "<<err<<endl;
exit(1);
}else
{
cout<<"uncompress() succeed: "<<endl;
cout<<(char*)uncompr<<endl;
}
return 0;
}
結果: