编译好的zlib库:
https://download.youkuaiyun.com/download/yuxing55555/11938358
参考源码中的示例:zlib-1.2.11/test/example.c
压缩,解压缩及其测试:
在.pro中添加:
ZLIB_DIR = F:/zlib/qt5.3/lib-debug
INCLUDEPATH += $${ZLIB_DIR}/include
LIBS += -L$${ZLIB_DIR}/lib \
libzlib
#include "zlib.h"
#include <stdio.h>
#include <iostream>
#ifdef STDC
# include <string.h>
# include <stdlib.h>
#endif
#define CHECK_ERR(err, msg) { \
if (err != Z_OK) { \
fprintf(stderr, "%s error: %d\n", msg, err); \
exit(1); \
} \
}
//压缩
char* Compress(char* src,int srcLen, int* comprLen){
int compressrate = 2;
int err;
int len = strlen(src) + 1;
std::cout << "len:"<<len<<",srcLen:"<<srcLen<<std::endl;
if(len != srcLen){
std::cout << "strlen != srcLen" << std::endl;
}
*comprLen = len*compressrate*sizeof(int);
std::cout << "ori comprLen:" << *comprLen << std::endl;
Byte *compr = (Byte*)calloc((uInt)(*comprLen), 1);
if (compr == Z_NULL) {
printf("out of memory\n");
return NULL;
}
err = compress(compr,(uLong*)comprLen,(const Bytef*)src,(uLong)len);
CHECK_ERR(err, "compress");
return (char*)compr;
}
//解压缩
char* Uncompress(char* compr, int comprLen,int& uncomprLen){
int compressrate = 2;
uncomprLen = comprLen * compressrate * sizeof(int);
std::cout << "ori uncomprLen:" << uncomprLen << std::endl;
Byte *uncompr = (Byte*)calloc((uInt)(uncomprLen), 1);
if (uncompr == Z_NULL) {
printf("out of memory\n");
return NULL;
}
int err;
err = uncompress(uncompr, (uLong*)(&uncomprLen),
(Byte*)compr, (uLong)comprLen);
CHECK_ERR(err, "uncompress");
return (char*)uncompr;
}
int main(int argc, char *argv[])
{
//测试
char* test = "hello,world";
int srcLen = strlen(test)+1;
int comprLen = 0;
char* compress = Compress(test,srcLen,&comprLen);
printf("compress(): %s %d\n", compress,comprLen);
int uncomprLen = 0;
char* uncompress = Uncompress(compress,comprLen,uncomprLen);
printf("uncompress(): %s %d\n", uncompress,uncomprLen);
if(compress != NULL){
free(compress);
}
if(uncompress != NULL){
free(uncompress);
}
return 0;
}