使用zib压缩文件

使用zib压缩文件成gzip;同时使用zlib中的deflate(压缩)函数和inflate(解压)函数,压缩解压文件中的内容

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

#include "stdafx.h"
#include <iostream>
#include <string>
#include "zlib.h" //导入zlib.lib之后,把zlib.h头文件包含
#include <fstream>

#define CHUNK 16384

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	char mid[CHUNK], out[CHUNK], in[CHUNK], hc[] = {'\n'}; //设置输入和输出buf

	string src_file = "E:\\Test_2_project\\src.txt"; //源文件路径
	fstream p_src_stream(src_file, ios::in); //读方式打开源文件
	if (!p_src_stream)
	{
		std::cout << "open file failed" << endl;
		return -1;
	}

	char *zip_file = "E:\\Test_2_project\\test.gz"; //压缩结果路径
	string des_file = "E:\\Test_2_project\\dest.txt";
	fstream p_dest_stream(des_file, ios::out); //写方式打开

	gzFile gzfp = gzopen(zip_file,"wb");//打开gz文件

	if (!gzfp)
	{
		cout << "open zip file failed" << endl;
		return -1;
	}

	cout << "gztell:" << gztell(gzfp) << endl;  

	while (1) {
		p_src_stream.getline(in, CHUNK); //读入数据
		//cout << "in: " << in << endl;
		//cout << "写入大小: " << gzwrite(gzfp, in, strlen(in) + 1) << endl;
		gzwrite(gzfp, in, strlen(in) + 1); //数据buf压入gz文件中
		gzwrite(gzfp, hc, 1);

		z_stream stream;
		stream.zalloc = Z_NULL;
		stream.zfree = Z_NULL;
		stream.opaque = Z_NULL;

		deflateInit(&stream, Z_DEFAULT_COMPRESSION); //压缩初始化
		stream.avail_in = strlen(in) + 1; //压缩函数结构体设置
		stream.next_in = (Bytef *)in;
		stream.avail_out = sizeof(mid);
		stream.next_out = (Bytef *)mid;

		deflate(&stream, Z_FINISH); //压缩
		//deflate(&stream, Z_NO_FLUSH);
		deflateEnd(&stream);

		z_stream strm;
		strm.zalloc = Z_NULL;
		strm.zfree = Z_NULL;
		strm.opaque = Z_NULL;

		inflateInit(&strm); //解压初始化
		strm.avail_in = strlen(mid) + 1;
		strm.next_in = (Bytef *)mid;
		strm.avail_out = sizeof(out);
		strm.next_out = (Bytef *)out;

		//inflate(&strm, Z_NO_FLUSH);
		inflate(&strm, Z_FINISH); //解压
		inflateEnd(&strm);
		//cout << "out: " << out << endl;

		if (p_dest_stream.is_open())
		{
			p_dest_stream << out << endl;
		}

		if (p_src_stream.eof())
			break;
	};
	p_src_stream.close(); //关闭文件
	p_dest_stream.close();
	gzclose(gzfp);
	system("pause");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值