zlib简单使用方法,生成gz压缩包

程序功能:
1、将指定文件压缩成指定压缩包文件
2、从指定压缩文件读取内容。

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <zlib.h>
#include <time.h>
#include <errno.h>
#include <assert.h>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

// gzip格式
// (u16)MAGIC + (u8)DEFLATE + (u8)flag + (u32)time + (u8)deflate_flag + (u8)OS_CODE

int main(int argc, char *argv[])
{
	if (argc < 3)
	{
		printf("usage : %s src_file dst_file\n", argv[1]);
 
		return -1;
	}

#if 0
	string out;

	//open .gz file
    gzFile gzfp = gzopen(argv[1],"rb");
    if(!gzfp)
    {
        return false;
    }
 
    //read and add it to out
    unsigned char buf[1024];
    int have;
    while( (have = gzread(gzfp,buf,1024)) > 0)
    {
        out.append((const char*)buf,have);
    }
 
    //close .gz file
    gzclose(gzfp);

	cout<<out<<endl;
#endif

	stringstream out;

	ifstream file;

	file.open(argv[1]);
	if(file.is_open())
	{
		//file>>out;

		out<<file.rdbuf();
	}

	cout<<out<<endl;
	file.close();

	string str = out.str();
	cout<<str<<endl;

	gzFile gzfp = gzopen(argv[2],"wb");
    if(!gzfp)
    {
        return false;
    }
 
    //read and add it to out
    unsigned char buf[1024];
    int have;
    if( gzwrite(gzfp,str.c_str(),str.size()) > 0)
    {
		cout<<"ok"<<endl;
    }
 
    //close .gz file
    gzclose(gzfp);
	
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值