使用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;
}