项目中添加lib库
demo
// 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'};
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);
//gz方式打开文件
gzFile gzfp = gzopen(zip_file,"wb");
if (!gzfp)
{
cout << "open zip file failed" << endl;
return -1;
}
cout<<"gztell:"<<gztell(gzfp)<<endl;
while (1) {
//文件内容读入内存in中
p_src_stream.getline(in, CHUNK);
//cout << "in: " << in << endl;
//压缩成gz文件
gzwrite(gzfp, in, strlen(in) + 1);
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;
}