现在的位置: 首页 > 综合 > 正文

使用zlib库进行数据压缩

2013年10月14日 ⁄ 综合 ⁄ 共 2134字 ⁄ 字号 评论关闭

使用zlib库进行数据压缩

zlib is designed to be a free, general-purpose, legally unencumbered -- that is, not covered by any patents -- lossless data-compression library for use on virtually any computer hardware and operating system. The zlib data format is itself portable across platforms.

那么如何使用它来进行数据压缩呢?

首先,去http://www.zlib.net/下载最新的Release版本,压缩完解压缩到一个文件目录

如果你在Linux下工作,那么编译前,请先看看目录下面的MakeFile文件,用文本打开(命令行下less),可以看到里面一些句子:

# To compile and test, type:
#    ./configure; make test
# The call of configure is optional if you don't have special requirements
# If you wish to build zlib as a shared library, use: ./configure -s

# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type:
       #    make install
       # To install in $HOME instead of /usr/local, use:
       #    make install prefix=$HOME

很简单,要编译安装linux下的静态库(.a)文件,那么在命令行下输入 ./configure;make;make install;就可以了,而如果要编译安装共享库(.so,类似windows下面的.dll),那么在命令行下输入 ./configure -s;make;make install;如果出现的都是Yes,那么就成功了。

在windows下编译将更简单,打开目录下projects/visualc6下的zlib.dsw,用VC6打开,然后在Build菜单下,选择Configurations,然后选择你要生成的类型就好了。vs2003/vs2005,下类似。

使用zlib,写一段简单的代码测试看看

#i nclude <stdio.h>
#i nclude "zlib.h"

int main()
{
     //原始数据
     const unsigned char strSrc[]="hello world!/n/
aaaaa bbbbb ccccc ddddd aaaaa bbbbb ccccc ddddd中文测试 中文测试/
aaaaa bbbbb ccccc ddddd aaaaa bbbbb ccccc ddddd中文测试 中文测试/
aaaaa bbbbb ccccc ddddd aaaaa bbbbb ccccc ddddd中文测试 中文测试/
aaaaa bbbbb ccccc ddddd aaaaa bbbbb ccccc ddddd中文测试 中文测试";

     unsigned char buf[1024]={0},strDst[1024]={0};
     unsigned long srcLen=sizeof(strSrc),bufLen=sizeof(buf),dstLen=sizeof(strDst);

      printf("Src string:%s/nLength:%d/n",strSrc,srcLen);
     //压缩
      compress(buf,&bufLen,strSrc,srcLen);
      printf("/nAfter Compressed Length:%d/n",bufLen);
      printf("Compressed String:%s/n",buf);
     //解压缩
      uncompress(strDst,&dstLen,buf,bufLen);
      printf("/nAfter UnCompressed Length:%d/n",dstLen);
      printf("UnCompressed String:%s/n",strDst);
     return 0;
}

编译这段代码时要注意,假设你在windows下并使用静态库(.lib)连接,那么在vc6下,需要把zlib.lib文件放到你的代码目录下,并把zlib.h、zconf.h加入到workspace中,并且设置项目属性:project-settings-link-category选择input,然后在library modules中的最后面输入一个空格和zlib.lib,并在lgnore libraries输入MSVCRT,原因是这个默认库和zlib会有冲突!设置好以后直接编译运行就行了

如果你在linux下面,那么把zlib.h、zconf.h、libz.a、test.cpp都放在同一个目录,然后在命令行输入以下命令,然后运行./test看看吧

g++ *.cpp libz.a -g -o test

 

 

 

 

 

 

 

抱歉!评论已关闭.