当前位置: 首页 > news >正文

调用Zlib库接口压缩、解压缩(C++源码)

1、概述

有些场景需要压缩、解压缩,本例中调用Zlib库接口实现,使用Zlib的静态库。

整体vs工程,后面上传到我的资源。
 

2、代码

2.1、调用示例

    // 调用示例: 压缩std::string out;std::string srcBuf = "123456ABC";MyZlibUtil::CompressBuf(srcBuf, out);cout << "CompressBuf out:" << out << endl;// 调用示例: 解压缩std::string src1 = out;std::string out1;MyZlibUtil::UncompressBuf(src1, out1);cout << "CompressBuf out:" << out1 << endl;

2.2、源码

#ifndef MyZlib_Util_h_
#define MyZlib_Util_h_#include <string>class MyZlibUtil
{
public:MyZlibUtil() = delete;~MyZlibUtil() = delete;public:static bool CompressBuf(const std::string& strSrcBuf, std::string& strOutBuf);static bool UncompressBuf(const std::string& strSrcBuf, std::string& strDestBuf);
};
#endif // !MyZlib_Util_h_
#include "MyZlibUtil.h"
#include "zlib.h"
#include <memory>constexpr size_t MAX_COMPRESS_BUF_SIZE = 20 * 1024 * 1024;bool MyZlibUtil::CompressBuf(const std::string& strSrcBuf, std::string& strOutBuf)
{if (strSrcBuf.empty() || strSrcBuf.length() > MAX_COMPRESS_BUF_SIZE){return false;}// 估算压缩数据的最大可能大小// 它返回一个上界值,保证原始数据压缩后不会超过这个长度uLongf destLen = compressBound(strSrcBuf.length());std::unique_ptr<unsigned char, std::default_delete<unsigned char[]>> buf(new unsigned char[destLen]);int ret = compress(buf.get(), &destLen, (const Bytef*)strSrcBuf.c_str(), strSrcBuf.length());if (ret != Z_OK){return false;}strOutBuf.clear();strOutBuf.append((char*)buf.get(), destLen);return true;
}bool MyZlibUtil::UncompressBuf(const std::string& strSrcBuf, std::string& strDestBuf)
{if (strSrcBuf.empty() || strSrcBuf.length() > MAX_COMPRESS_BUF_SIZE){return false;}uLongf len = strSrcBuf.length() * 8;std::unique_ptr<unsigned char, std::default_delete<unsigned char[]>> upDestBuf(new unsigned char[len]);int ret = uncompress(upDestBuf.get(), &len, (const Bytef*)strSrcBuf.c_str(), strSrcBuf.length());if (ret != Z_OK){return false;}strDestBuf.clear();strDestBuf.append((char*)upDestBuf.get(), len);return true;
}

http://www.dtcms.com/a/523650.html

相关文章:

  • flume的log4j日志无输出排查
  • 一个域名可以做两个网站吗天津人事考试网
  • whisper 模型处理音频办法与启示
  • linux rt任务调度器
  • 金融智能体技术解读:十大应用场景与AI Agent架构设计思路
  • 永磁同步电机(PMSM)在MATLAB中的高级调参策略与实践
  • 李宏毅机器学习笔记31
  • 【timecode】两种不同的时间码格式:“`00:00:00`” 和 “`00:00:00:00`”
  • 个人网站 不用备案深圳建设网站和公众号
  • npm 安装 canvas 报错 node-gyp ERR! 的解决方法(Windows 系统)
  • 编辑器汇总:Neovim、Helix、Vim、LazyVim、Kakoune、nb、Lite XL
  • 如何开发一个自己的包并发布到npm
  • 商城型网站的概念企业信息平台登录
  • Docker MySQL 单主从及分表函数
  • UE5 蓝图-11:本汽车蓝图的事件图表,汽车拆分事件,染色事件(绿蓝黄青)。
  • CDC 实时数据同步与小时级统计方案(Flink 1.13.5 + MySQL 8.0)
  • Redis之String 类型入门与实战,由基础语法快速掌握再到缓存加速/验证码防刷/计数统计场景应用
  • 【Qt | .pro文件】Qt项目文件详解:pro文件与pri文件
  • SpringAI2-Spring AI-聊天模型:ChatClient,流式编程,ChatModel
  • [MySQL] 事务和视图
  • 建设网站的特色wordpress域名网站搬家
  • 记录画图笔记
  • 【江苏政务服务网-注册_登录安全分析报告】
  • redisson介绍
  • 20251020二分总结
  • Android 基于清单文件mate-data数据共享
  • Android中Window和LayoutParams的常用属性及常用方法介绍
  • MySQL的安装与卸载
  • 单调栈详解【C/C++】
  • 智慧用电平台让安全走在事故前面