zlib在CentOS7下安装配置及C++编写实现一个简单压缩解压缩demo(截图,附源代码)

zlib目前最新的版本V1.2.11,官网地址:https://www.zlib.net/

zlib被设计成一个免费的、通用的、法律上不受阻碍(即没有被任何专利覆盖) 的无损数据压缩库。zlib几乎适用于任何计算器硬件和操作系统。

zlib支持linux,windows,solaris,macOS等等环境,支持C++,.net, delphi, java,perl, python等待语言,非常强大。

1.centOS7下zlib安装配置

centos下安装zlib有两种方法,用yum指令;到官网下载。

1.1指令安装

yum install -y zlib zlib-devel

官网下载

注意一个是zlib.net,如果下不动的话,可以到sourceforge镜像网站试试,这里我选择的是zlib-1.2.11.tar.gz

image.png

1.2解压安装

tar -xzvf zlib-1.2.11.tar.gz

解压出来可以看到里面有examples和test目录,里面都是示例可以查看。

image.png

2.编写demo

2.1.新建Clion工程

我是用的clion,新建C++ executable程序。

扫描二维码关注公众号,回复: 10186509 查看本文章

image.png

2.2拷贝源文件

在目录zlib-1.2.11/contrib/minizip下拷贝源文件到工程目录下,拷贝zip.h, zip.c, unzip.h, unzip.c, ioapi.h, ioapi.c

和目录zlib-1.2.11/zlib.h

image.png

2.3新建zipoperator.h, zipoperator.cpp文件,用于写具体的压缩,解压缩函数

image.png

2.4编写main函数,用于测试

int main() {
    string strZipPath = "/home/ji/UpTransPack/";
    string strZipFileName = "2020001.zip";
    Byte bufData[512]={0};
    int bufLen = 512;
    for(int i=0;i<100;i++)
    {
        bufData[i]=i;
    }
    cout << "begin compress byte stream to file" << endl;
    if( 0!= compress_file(strZipPath.c_str(), strZipFileName.c_str(), bufData, bufLen) )
    {
        cout<<"create zip file faild!"<<endl;
        return -1;
    }
    cout << "create zip file success"<<endl;

    cout << "begin uncompress zip file to byte stream" << endl;
    int nLen = 0;
    Byte* ibuf = nullptr;
    unzFile zf = unzfile_open((strZipPath+strZipFileName).c_str(), nLen);
    ibuf = new Byte[nLen];
    if(zf == NULL)
    {
        cout<< "open the zip file faild!"<<endl;
        delete[] ibuf;
        return -2;
    }
    if( 0 != unzfile_extract(zf, (unsigned char*)ibuf, nLen) )
    {
        cout << "uncompress zip file faild" << endl;
        delete[] ibuf;
        return -2;
    }
    delete[] ibuf;
    return 0;
}

2.5编写CMakeLists

添加需要编译的.c文件

链接libz.so

image.png

2.6最后运行效果,将字节流添加到zip文件中,并从zip文件中解压出字节流。

image.png

最后,我们可以将字节流压缩到zip包里,从zip里解压出字节流,同样也可以将多个文件压缩到zip包里,从zip里解压出多个原始文件,只要看一下zlib提供的example稍微改动即可满足自己的应用场景。

演示源代码

发布了27 篇原创文章 · 获赞 9 · 访问量 4885

猜你喜欢

转载自blog.csdn.net/weixin_41761608/article/details/104995205