zlib日常使用中常常会遇到 缓冲区的问题,我们可以自定义一个字段保存原始数据大小来解决这个问题

// zlib_demo.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "zconf.h"
#include "zlib.h "
#include <string>
#include <stdio.h>
#include <iostream>

#pragma comment( lib, "zlib.lib")


/*
自定义zlib数据格式
两句话透明解决zlib数据压缩
*/

std::string my_zlib_compress(std::string data)
{
    if(data.size() == 0)
    {
        return data;
    }
    //计算压缩后的数据需要的大小
    uLong blen = compressBound(data.size()); 
    
    /*
    划分缓冲区
    我们这里多给四字节表示原数据大小
    */
    char *buf = (char*)malloc(blen + 4);
    *(unsigned int *)buf = data.size();//填充原始数据大小
    
    //压缩
    if(compress((Bytef *)buf + 4, &blen, (Bytef *)data.c_str(), data.size()) != Z_OK)
    {
        printf("compress failed!\n");
    }
    
    //填充封装好的数据
    std::string zipdata(buf, blen + 4);
    
    
    free(buf);
    
    return zipdata;
}
    
std::string my_zlib_decompress(std::string data)
{
    if(data.size() == 0)
    {
        return data;
    }
    //获取原始数据大小
    uLong n_size = *(unsigned int*)data.c_str();
    
    //申请空间
    char * buf = (char *)malloc(n_size);
    
    //解压数据
    if(uncompress((Bytef *)buf, &n_size, (Bytef *)data.c_str() + 4, data.size() - 4) != Z_OK)
    {
        printf("uncompress failed!\n");
    }
    
    //填充封装好的数据
    std::string zipdata(buf, n_size);
    
    
    free(buf);
    
    return zipdata;
}
    
int main()
{
    char str[] = "原始数据";
    std::cout
        << my_zlib_decompress(my_zlib_compress(str)).c_str()
        << std::endl;
    
    system("pause");
    return 0;
}
Last modification:November 24, 2018
如果觉得我的文章对你有用,请随意赞赏