zlib库compress和uncompress函数的使用方法

zlib(http://zlib.net/)提供了简洁高效的In-Memory数据压缩和解压缩系列API函数,很多应用都会用到这个库,其中compress和uncompress函数是最基本也是最常用的。不过很奇怪的是,compress和uncompress函数尽管已经非常的简单,却仍然有不少人用得不好,其实归根结底还是在于有些事情没有弄明白,这里大家先看下面的代码。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <zlib.h>

int main(int argc, char* argv[])
{
	char text[] = "zlib compress and uncompress test\nturingo@163.com\n2012-11-05\n";
	uLong tlen = strlen(text) + 1;	/* 需要把字符串的结束符'\0'也一并处理 */
	char* buf = NULL;
	uLong blen;

	/* 计算缓冲区大小,并为其分配内存 */
	blen = compressBound(tlen);	/* 压缩后的长度是不会超过blen的 */
	if((buf = (char*)malloc(sizeof(char) * blen)) == NULL)
	{
		printf("no enough memory!\n");
		return -1;
	}

	/* 压缩 */
	if(compress(buf, &blen, text, tlen) != Z_OK)
	{
		printf("compress failed!\n");
		return -1;
	}

	/* 解压缩 */
	if(uncompress(text, &tlen, buf, blen) != Z_OK)
	{
		printf("uncompress failed!\n");
		return -1;
	}

	/* 打印结果,并释放内存 */
	printf("%s", text);
	if(buf != NULL)
	{
		free(buf);
		buf = NULL;
	}

	return 0;
}
zlib处理的对象是Bytef*字节流,很多人遇到字符串就会混淆了,其实很简单,字节流是没有结束符的,需要配备长度信息,所以处理字符串的时候需要把结束符也当成一个普通的字节,这样计算长度的时候也需要算它一份。另外绝大部分人都想动态分配缓冲区,也就是说需要多少再给多少,其实zlib本身有提供compressBound函数用于计算压缩后缓冲区长度的上限值,不需要额外再设计一些不适当的预测算法,不过解压缩的时候没有提供长度的预测,由于compress和uncompress一般都是成对使用的,预先保存好原文的长度即可。

  • 9
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 25
    评论
C++20 并没有提供自带的 zlib ,但您可以使用第三方或手动编译 zlib 并链接到您的项目中。以下是一个使用第三方 zlib-ng 的 C++20 示例代码,可以用于压缩和解压缩数据: ```cpp #include <iostream> #include <cstring> #include <zlib-ng.h> int main() { const char* source = "Hello, world!"; const unsigned long sourceLen = strlen(source) + 1; // 加上字符串末尾的 '\0' unsigned long destLen = compressBound(sourceLen); // 预估压缩后的长度 char* dest = new char[destLen]; // 压缩数据 int ret = compress2((Bytef*)dest, &destLen, (const Bytef*)source, sourceLen, Z_BEST_COMPRESSION); if (ret != Z_OK) { std::cerr << "Compression failed." << std::endl; return 1; } std::cout << "Compressed data: " << dest << std::endl; // 解压缩数据 char* source2 = new char[sourceLen]; destLen = sourceLen; ret = uncompress((Bytef*)source2, &destLen, (const Bytef*)dest, destLen); if (ret != Z_OK) { std::cerr << "Decompression failed." << std::endl; return 1; } std::cout << "Decompressed data: " << source2 << std::endl; delete[] dest; delete[] source2; return 0; } ``` 在这个例子中,我们使用zlib-ng 提供的 compress2 和 uncompress 函数,实现了与上一个示例类似的功能。注意,与 zlib 不同,zlib-ng 的压缩函数需要传入一个压缩级别参数,这里我们传入了 Z_BEST_COMPRESSION,表示最高的压缩级别。 在实际使用中,您需要根据具体的和算法选择合适的函数和参数,并进行更加完整的错误处理和调试。
评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值