#include <zlib.h>
#include <iostream>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>

using namespace std;

#define RD_GZ_CHUNK  262144
#define RD_ZERO_INIT {0}

/* Compress gzip data */
/* data 原数据 ndata 原数据长度 zdata 压缩后数据 nzdata 压缩后长度 */
int gzcompress( Bytef *data, uLong ndata, 
   Bytef *zdata, uint64_t *nzdata )
{
    z_stream c_stream;
    int err = 0;
 
    if(data && ndata > 0) 
    {
        c_stream.zalloc = NULL;
        c_stream.zfree = NULL;
        c_stream.opaque = NULL;
        int iRet = -1;
        //只有设置为MAX_WBITS + 16才能在在压缩文本中带header和trailer
        if ( iRet = deflateInit2( &c_stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
                        MAX_WBITS + 16, 8, Z_DEFAULT_STRATEGY ) != Z_OK )
        {
            cout << "deflateInit2 return " << iRet  << endl;
            return -1;
        }

c_stream.next_in  = data;
        c_stream.avail_in  = ndata;
        c_stream.next_out = zdata;
        c_stream.avail_out  = *nzdata;
        while(c_stream.avail_in != 0 && c_stream.total_out < *nzdata)
        {
            if(deflate(&c_stream, Z_NO_FLUSH) != Z_OK) return -1;
        }
        if(c_stream.avail_in != 0) 
            return c_stream.avail_in;
        for(;;) 
        {
            if((err = deflate(&c_stream, Z_FINISH)) == Z_STREAM_END) 
                break;
            if(err != Z_OK) 
                return -1;
        }
        if(deflateEnd(&c_stream) != Z_OK) 
            return -1;
        *nzdata = c_stream.total_out;
        return 0;
    }
    return -1;
}

char * rd_gz_decompress ( const char *compressed, int compressed_len,
        uint64_t *decompressed_lenp )
{
        int pass = 1;
        char *decompressed = NULL;
        /* First pass (1): calculate decompressed size.
        *                 (pass-1 is skipped if *decompressed_lenp is
        *                  non-zero).
        * Second pass (2): perform actual decompression.
        */
        if (*decompressed_lenp != 0LLU)
                pass++;
        for (; pass <= 2 ; pass++) 
        {
                z_stream strm = RD_ZERO_INIT;
                gz_header hdr;
                char buf[512];
                char *p;
                int len;
                int r;
                if ((r = inflateInit2(&strm, 15+32)) != Z_OK)
                        goto fail;
                strm.next_in = (Bytef *)compressed;
                strm.avail_in = compressed_len;
                if ((r = inflateGetHeader(&strm, &hdr)) != Z_OK) 
                {
                        inflateEnd(&strm);
                        goto fail;
                }
                if (pass == 1) 
                {
                        /* Use dummy output buffer */
                        p = buf;
                        len = sizeof(buf);
                } 
                else 
                {
                        /* Use real output buffer */
                        p = decompressed;
                        len = (int)*decompressed_lenp;
                }
                do
                {
                        strm.next_out = (unsigned char *)p;
                        strm.avail_out = len;
                        r = inflate(&strm, Z_NO_FLUSH);
                        switch  (r)
                        {
                        case Z_STREAM_ERROR:
                        case Z_NEED_DICT:
                        case Z_DATA_ERROR:
                        case Z_MEM_ERROR:
                                inflateEnd(&strm);
                                goto fail;
                        }
                        if (pass == 2)
                        {
                                /* Advance output pointer (in pass 2). */
                                p += len - strm.avail_out;
                                len -= len - strm.avail_out;
                        }
                } while (strm.avail_out == 0 && r != Z_STREAM_END);
                if (pass == 1)
                {
                        *decompressed_lenp = strm.total_out;
                        if (!(decompressed = (char*)malloc((size_t)(*decompressed_lenp)+1)))
                        {
                                inflateEnd(&strm);
                                return NULL;
                        }
                        /* For convenience of the caller we nul-terminate
                        * the buffer. If it happens to be a string there
                        * is no need for extra copies. */
                        decompressed[*decompressed_lenp] = '\0';
                }
                inflateEnd(&strm);
        }
        return decompressed;
fail:
        if (decompressed)
                free(decompressed);
        return NULL;
}

int main( int argc, char ** argv )
{
    int iRet = -1;

char sBuffer[65536];
    memset( sBuffer, 0, sizeof( sBuffer ) );
   
    char * sOriginal = "Hello world!123456789001234567890123456789012345678901234567890";
     
    // compress it 
    uint64_t iCompressedLen = sizeof(sBuffer);

gzcompress( (Bytef*)sOriginal, strlen( sOriginal ), 
        (Bytef*)sBuffer,  &iCompressedLen );

cout << "sOriginal:" << sOriginal << ",iCompressedLen:" 
        << iCompressedLen  << endl;

uint64_t iDecompressedLen = 0;
    char *decompressed  = (char*)rd_gz_decompress ( sBuffer, 
        iCompressedLen, &iDecompressedLen );

if ( decompressed != NULL )
    {
        cout << "after decrypt is " << decompressed  
            << ", iDecompressedLen is " << iDecompressedLen << endl;
    }
    else
    {
        cout << "rd_gz_decompress failed."  << endl;
    }
    
    return iRet;
}

make.sh

g++ main.cpp -lz

sh -x make.sh

./a.out 
sOriginal:Hello world!123456789001234567890123456789012345678901234567890,iCompressedLen:46
after decrypt is Hello world!123456789001234567890123456789012345678901234567890, iDecompressedLen is 63

gzip 压缩解压代码示例相关推荐

  1. GZip 压缩解压 --- Pako 的压缩解压

    一.GZip压缩解压 package java调用JS;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream ...

  2. Linux gzip压缩/解压 *.gz文件详解

    gzip 是linux中常见的压缩/解压工具,最常见的使用对象是*.gz格式的文件,这里简单介绍下它最常见的用法, GZIP(1) General Commands Manual GZIP(1) NA ...

  3. 字符串GZIP压缩解压

    c# /// <summary>/// 字符串压缩解压/// </summary>public class Zipper{public static string Compre ...

  4. java gzip 压缩解压工具类

    因为觉得简单,本想抱着百度直接拿过来用的心态,结果发现网上的代码都转载自同一份,且埋了一个坑,你不仔细去梳理,很难发现. mark下需要注意的两点: 1. 编码/解码,压缩/解压缩是成对出现的 编码: ...

  5. C# GZip 压缩 / 解压

    有时候我们需要去压缩数据 如视频/音频/内容 等信息 不少应用于套接字编程 不过微软为我 们提供了一个用于解压缩的类GZIP不过这东西是很多年以前就开了源代码的 如RAR则是借 鉴其算法修改增强的一个 ...

  6. python3 gzip 压缩/解压

    import gzip t = gzip.compress('{"key":value""}'.encode())print(gzip.decompress(t ...

  7. Ubuntu使用gzip与bzip2与rar和tar压缩解压

    目录 1.gzip压缩解压 2.bzip2压缩解压 3.rar压缩解压 tar归档压缩与解压包 1.gzip压缩解压 因为都是系统自带的我们不需要安装: ls 看一下目录当前的文件,创建一个 touc ...

  8. python压缩文件tar_python 实现tar文件压缩解压的实例详解

    python 实现tar文件压缩解压的实例详解 python 实现tar文件压缩解压的实例详解 压缩文件: import tarfile import os def tar(fname): t = t ...

  9. Asp.net 2.0 C#实现压缩/解压功能

    Asp.net 2.0 C#实现压缩/解压功能 (示例代码下载) (一). 实现功能 对文件及目录的压缩及解压功能 (二). 运行图片示例 (三).代码 1. 压缩类   1/**//// <s ...

最新文章

  1. 每日一皮:进来说说昨天你是怎么过的?
  2. 鑿婂瓙鏇版祴璇曡崏绋縶29C28FD771BA4B0D8693}
  3. go get报错unrecognized import path “golang.org/x/net/context”…
  4. css3 多列布局使用
  5. javaweb学习总结五(内省、beanUtils工具包)
  6. TrustBase团队完成subscript语言的Web3基金会Grant资助计划项目交付
  7. I/O多路复用技术是什么?
  8. android购物车栏,Android怎么实现二级列表购物车功能
  9. js获得浏览器高度和宽度 参数
  10. 量子计算机未来猜想,太厉害了吧?这台量子计算机能预测16种不同的未来!
  11. matlab查询函数用法,matlab函数用法总结
  12. C++设计模式基础和模式设计基本原则
  13. 这款扩音器让我见识了什么才是地摊神器,震撼的声音通透整条街
  14. 2017年看的tracking论文
  15. html怎么把图片做成抖动效果,js实现鼠标触发图片抖动效果的方法
  16. 思科PC远程控制交换机和路由器
  17. win8\win server 2012添加【中文--美式键盘】
  18. 【陈鹏老师精益项目实战】华中区化工企业精益设备TPM项目年度总结大会
  19. layui图片管理器
  20. OpenCV—python 图像压缩

热门文章

  1. adb操作提示Read-only file system问题
  2. ZGC都出来了,你还不懂G1?
  3. R6034 又来了.
  4. Quectel BC25 系列 尺寸紧凑、功耗超低 NB-IoT 无线通信模块[移远通信]
  5. BeautifulSoup说明
  6. 【JDBC】JDBC 简介 ( JDBC 概念 | JDBC 本质 | 使用 JDBC 操作数据库的好处 | JDBC 提供的 API 组件 )
  7. Verify the connector‘s configuration, identify and stop any process that‘s listening on port 80, or
  8. python-docx 设置Table 边框样式、单元格边框样式
  9. 【Web项目】点餐系统
  10. DAE系统的设计-豆瓣首席架构师洪强宁