yeguoxiong的个人主页

http://www.qtcn.org/bbs/u/41539  [收藏] [复制]

yeguoxiong

  • 59

    关注

  • 179

    粉丝

  • 432

    访客

  • 等级:侠客
  • 总积分:147
  • 男,1985-07-02
  • 四川

最后登录:2024-04-15

更多资料

日志

zlib库里的compress函数与uncompress函数介绍

2013-04-25 14:26
1、zlib 是通用的压缩库,提供了一套 in-memory 压缩和解压函数,并能检测解压出来的数据的完整性(integrity)。zlib 也支持读写 gzip (.gz) 格式的文件。下面介绍两个最有用的函数——compress 和 uncompress。

2、int compress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

    compress函数将 source 缓冲区中的内容压缩到 dest 缓冲区。 sourceLen 表示source 缓冲区的大小(以字节计)。注意函数的第二个参数 destLen 是传址调用。当调用函数时,destLen表示 dest 缓冲区的大小,destLen > (sourceLen + 12)*100.1%。当函数退出后,destLen 表示压缩后缓冲区的实际大小。此时 destLen / sourceLen 正好是压缩率。

compress 若成功,则返回 Z_OK;若没有足够内存,则返回 Z_MEM_ERROR;若输出缓冲区不够大,则返回 Z_BUF_ERROR。

3、int uncompress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

    uncompress 函数将 source 缓冲区的内容解压缩到 dest 缓冲区。sourceLen 是 source 缓冲区的大小(以字节计)。注意函数的第二个参数 destLen 是传址调用。当调用函数时,destLen 表示 dest 缓冲区的大小, dest 缓冲区要足以容下解压后的数据。在进行解压缩时,需要提前知道被压缩的数据解压出来会有多大。这就要求在进行压缩之前,保存原始数据的大小(也就是解压后的数据的大小)。这不是 zlib 函数库的功能,需要我们做额外的工作。当函数退出后, destLen 是解压出来的数据的实际大小。

    uncompress 若成功,则返回 Z_OK ;若没有足够内存,则返回 Z_MEM_ERROR;若输出缓冲区不够大,则返回 Z_BUF_ERROR。若输入数据有误,则返回 Z_DATA_ERROR。
4、 测试代码


[font='Courier New']#include <cstring>
#include <cstdlib>
#include <iostream>
#include "zlib.h"
using namespace std;
int main()
{
    int err;
    Byte compr[200], uncompr[200];
    uLong comprLen, uncomprLen;
    const char* hello = "12345678901234567890123456789012345678901234567890";
    uLong len = strlen(hello) + 1;
    comprLen  = sizeof(compr) / sizeof(compr[0]);

    err = compress(compr, &comprLen, (const Bytef*)hello, len);
    if (err != Z_OK) {
        cerr << "compess error: " << err';
        exit(1);
    }
    cout << "orignal size:" << len [font='Courier New']<< "compressed size : " <<comprLen;

    strcpy( (char*)uncompr, "garbage" );
    err = uncompress(uncompr, &uncomprLen, compr, comprLen);
    if (err != Z_OK) {
        cerr << "uncompess error: " << err << '\n';
        exit(1);
    }
    cout << "orignal size:" <<len[font='Courier New']<< " uncompressed size:" <<uncomprLen ;
    if (strcmp((char*)uncompr, hello))
    {

        cerr << "BAD uncompress";
        exit(1);
    } else
    {

        cout << "uncompress() succeed: " << (char *)uncompr;
    }




分类:默认分类|回复:0|浏览:3697|全站可见|转载
 

Powered by phpwind v8.7 Certificate Copyright Time now is:05-03 10:06
©2005-2016 QTCN开发网 版权所有 Gzip disabled