使用zlib压缩文件

本文详细介绍了如何在C++中使用zlib库进行文件压缩操作,包括所需的头文件引用和源代码实现,适用于Linux环境。
摘要由CSDN通过智能技术生成

头文件

//压缩
int CompressFile(const char* source, const char* dest);

//解压缩
int UnCompressFile(const char* source, const char* dest);

源文件

#include <stdio.h>
#include "zlib-1.2.13/zlib.h"

typedef unsigned char byte;

//压缩
int CompressFile(const char* source, const char* dest)
{
	int func_ret = 0;

	FILE *source_fp = fopen(source, "rb");
	if (source_fp == NULL)
	{
		return -1;
	}

	FILE *dest_fp = fopen(dest, "wb");
	if (dest_fp == NULL)
	{
		fclose(source_fp);

		return -1;
	}

	while (true)
	{
		byte *buf = new byte[1024 * 1024];

		int fread_ret = fread(buf, sizeof(byte), 1024 * 1024, source_fp);

		if (fread_ret == 0)
		{
			break;
		}

		uLong out_buf_long = 1024 * 1024;
		byte *out_buf = new byte[out_buf_long];

		if (compress(out_buf, &out_buf_long, buf, fread_ret) != Z_OK)
		{
			func_ret = -1;
			
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值