实用辅助类-gzip解压类封装

本类在zlib库基础上进行了一层封装,以便在内存中解压gzip数据

content_decoder.h

#ifndef __CONTENT_DECODER_H__
#define __CONTENT_DECODER_H__

#include <string>

class gzip_decoder
{
public:
    gzip_decoder(size_t uncompress_buff_len = 1024);

    ~gzip_decoder();

    bool ungzip(unsigned char* gzdata, size_t gzdata_len, std::string& out_data);

protected:
private:
    const size_t uncompress_buff_len_;
    unsigned char* uncompress_buff_;
};

#endif

content_decoder.cpp

#include "content_decoder.h"
#include <stdlib.h>
#include "zlib.h"


gzip_decoder::gzip_decoder(size_t uncompress_buff_len)
:uncompress_buff_len_(uncompress_buff_len),
uncompress_buff_(NULL)
{
    uncompress_buff_ = (unsigned char*)malloc(uncompress_buff_len_);
}

gzip_decoder::~gzip_decoder()
{
    if (uncompress_buff_)
    {
        free(uncompress_buff_);
    }
}

bool gzip_decoder::ungzip(unsigned char* gzdata, size_t gzdata_len, std::string& out_data)
{
    int err;
    unsigned long out_count = 0;
    z_stream d_stream = {0}; /* decompression stream */

    d_stream.zalloc = (alloc_func)0;
    d_stream.zfree = (free_func)0;
    d_stream.opaque = (voidpf)0;
    d_stream.next_in = gzdata;
    d_stream.avail_in = gzdata_len;
    d_stream.avail_out = uncompress_buff_len_;
    d_stream.next_out = uncompress_buff_;

    if(inflateInit2(&d_stream, 47) != Z_OK)
        return false;

    out_data.clear();

    while (d_stream.total_in < gzdata_len)
    {
        if((err = inflate(&d_stream, Z_SYNC_FLUSH)) == Z_STREAM_END)
        {
            out_data.append((const char*)uncompress_buff_, d_stream.total_out - out_count);
            err = inflateEnd(&d_stream);
            break;
        }

        if(err == Z_OK)
        {
            out_data.append((const char*)uncompress_buff_, d_stream.total_out - out_count);
            out_count = d_stream.total_out;
            d_stream.avail_out = uncompress_buff_len_;
            d_stream.next_out = uncompress_buff_;
        }
        else
        {
            goto unzip_exit;
        }
    }

unzip_exit:
    return err == Z_OK;
}

原文: http://blog.chinaunix.net/uid-21525518-id-1824656.html


源码如下源码下载:http://blogimg.chinaunix.net/blog/upfile2/100225140518.rar

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值