c++ zlib(qt)压缩与解压缩

本文提供了一个使用C++与Qt进行文件压缩和解压缩的示例,通过Zlib库实现。代码展示了如何读取源文件、压缩数据到新文件,并从压缩文件中解压缩数据。
#include <QtCore/QCoreApplication>
#include "zlib.h"
#include "stdio.h"
#include <iostream>
using   namespace   std;

#define MaxBufferSize 999999

void Test1();
void Test2();

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //Test1();
    Test2();
    
    return a.exec();
}

//c++ zlib
void Test1()
{
    FILE* File_src;
    FILE* File_compress;
    FILE* File_uncompress;

    unsigned long len_src;
    unsigned long len_compress;
    unsigned long len_uncompress;

    unsigned char *buffer_src  = new unsigned char[MaxBufferSize];
    unsigned char *buffer_compress  = new unsigned char[MaxBufferSize];
    unsigned char *buffer_uncompress = new unsigned char[MaxBufferSize];

    File_src = fopen("src.txt","r");
    File_compress = fopen("compress.txt","w");
    File_uncompress = fopen("uncompress.txt","w");

    //compress
    len_src = fread(buffer_src,sizeof(char),MaxBufferSize-1,File_src);
    compress(buffer_compress,&len_compress,buffer_src,len_src);
    fwrite(buffer_compress,sizeof(char),len_compress,File_compress);
    cout << "normal zlib:" << endl;
    cout << "src:\n" << buffer_src << ",length:" << len_src << endl << endl;
    cout << "compress:\n" << buffer_compress << ",length:" << len_compress << endl << endl;

    //uncompress
    uncompress(buffer_uncompress,&len_uncompress,buffer_compress,len_compress);
    fwrite(buffer_uncompress,sizeof(char),len_uncompress,File_uncompress);
    cout << "uncompress:\n" << buffer_uncompress << ",length:" << len_uncompress << endl << endl;

    fclose(File_src);
    fclose(File_compress);
    fclose(File_uncompress);
}

//qt zlib
void Test2()
{
    QByteArray src;
    src.append("中华人民共和国,china mobile,123456");

    unsigned long len_compress;
    unsigned long len_uncompress;

    unsigned char *buffer_compress  = new unsigned char[MaxBufferSize];
    unsigned char *buffer_uncompress = new unsigned char[MaxBufferSize];

    compress(buffer_compress,&len_compress,(Bytef*)src.data(), src.length());
    uncompress(buffer_uncompress,&len_uncompress,buffer_compress,len_compress);

    cout << "qt zlib:" << endl;
    cout << "src:\n" << src.data() << ",length:" << src.size() << endl << endl;
    cout << "compress:\n" << buffer_compress << ",length:" << len_compress << endl << endl;
    cout << "uncompress:\n" << buffer_uncompress << ",length:" << len_uncompress << endl << endl;
}

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值