使用zlib对字符串进行压缩

编译好的zlib库:
https://download.csdn.net/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;
}


在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力减肥的小胖子5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值