C++QT实现压缩文件、文件夹和解压缩操作

news2025/2/28 15:32:25

一、前言

QZipWriter是用来压缩文件的类,需要在安装Qt是选择Sources源码安装。否则,无法使用QZipWriter。

 

1. QZipWriter函数说明
1.1 构造方法:

QZipWriter(const QString &fileName, QIODevice::OpenMode mode = (QIODevice::WriteOnly | QIODevice::Truncate) );
QZipWriter(QIODevice *device);

fileName:保存zip文件的地址。

QIODevice 是 QFile 的父类,因此在构造 QZipWriter类的对象时,可以传递一个 QFile 类的对象。

本文福利,费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QT嵌入式开发,Quick模块等等)↓↓↓↓↓↓见下面↓↓文章底部点击费领取↓↓

1.2 设置压缩权限:

enum CompressionPolicy {
     AlwaysCompress,
     NeverCompress,
     AutoCompress
};
void setCompressionPolicy(CompressionPolicy policy);
CompressionPolicy compressionPolicy() const;


1.3 添加文件:

 void addFile(const QString &fileName, const QByteArray &data);


1.4 添加目录:

void addDirectory(const QString &dirName);


如果需要将文件压缩到lib目录下,那么可以这样操作:

  writer->addDirectory("lib");
  writer->addFile("lib/" + fileName, const QByteArray &data);

这样压缩,就可以在压缩包当中看到lib目录,并且文件在lib目录下。

二、实现方式

通过Qt自带的库来实现,使用多线程方式,通过信号和槽来触发压缩与解压缩,并将压缩和解压缩结果回传过来。
使用的类:

#include "QtGui/private/qzipreader_p.h"
#include "QtGui/private/qzipwriter_p.h"

三、具体步骤

1、在.pro文件中添加模块gui-private

QT       += core gui gui-private

2、通过QObject方式创建多线程实现压缩与解压缩类

CompreDecompreFileThread.h

#ifndef COMPREDECOMPREFILETHREAD_H
#define COMPREDECOMPREFILETHREAD_H

#include <QObject>
#include "QtGui/private/qzipreader_p.h"
#include "QtGui/private/qzipwriter_p.h"
#include <QFileInfoList>
#include <QDir>
#include <QFile>
#include <QThread>
class CompreDecompreFileThread : public QObject
{
    Q_OBJECT
public:
    typedef enum
    {
        success,
        failed,
        running
    }ResultE;
signals:
    void compression_res_signal(ResultE res,quint8 progress,QString remarks = nullptr);
    void decompression_res_signal(ResultE res,quint8 progress,QString remarks = nullptr);
public slots:
    /*
     * 压缩文件
     */
    void compression_file_run(QString srcPath,QString destPath);
    /*
     * 解压文件
     */
    void decompression_file_run(QString srcPath,QString destPath);
public:
    explicit CompreDecompreFileThread(QObject *parent = nullptr);
private:
    /*
     * 遍历压缩文件
     */
    QFileInfoList ergodic_compression_file(QZipWriter *writer,QString rootPath,QString filePath);

private:
    QZipWriter *zipWriter = nullptr;
    QZipReader *zipReader = nullptr;
};

#endif // COMPREDECOMPREFILETHREAD_H

CompreDecompreFileThread.cpp

#include "compredecomprefilethread.h"
#include <QDebug>
#include <QIODevice>

CompreDecompreFileThread::CompreDecompreFileThread(QObject *parent)
    : QObject{parent}
{
    qRegisterMetaType<ResultE>("ResultE");
}

QFileInfoList CompreDecompreFileThread::ergodic_compression_file(QZipWriter *writer, QString rootPath, QString filePath)
{
    QDir dir(filePath);          //遍历各级子目录
    QDir fileDir(filePath);    //遍历子目录中所有文件

    //先遍历文件夹 添加进widget
    QFileInfoList fileList=dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
    QFileInfoList folderList = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);   //获取当前所有目录 QDir::Dirs 0x001 列出目录;


    for(int i = 0; i != folderList.size(); i++)         //自动递归添加各目录到上一级目录
    {
        QString namepath = folderList.at(i).absoluteFilePath();    //获取路径
        QFileInfo folderinfo= folderList.at(i);
        QString name=folderinfo.fileName();      //获取目录名


        QStringList list = folderinfo.absoluteFilePath().split(rootPath);
        //qDebug()<<"Dir:"<<folderinfo.absoluteFilePath().remove(list.at(0));
        writer->addDirectory(folderinfo.absoluteFilePath().remove(list.at(0)));

        QFileInfoList child_file_list = ergodic_compression_file(writer,rootPath,namepath);          //进行递归 递归这个文件夹
        fileList.append(child_file_list);
        //  file_list.append(name);

    }
    /*添加path路径文件*/

    fileDir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);        //获取当前所有文件
    fileDir.setSorting(QDir::Name);
    QFileInfoList _fileList = fileDir.entryInfoList();
    for (int i = 0; i < _fileList.size(); ++i) //将当前目录中所有文件添加到treewidget中
    {
        QFileInfo fileInfo = _fileList.at(i);

        QFile file(fileInfo.absoluteFilePath());
        if(file.open(QIODevice::ReadOnly))
        {
            QStringList list = fileInfo.absoluteFilePath().split(rootPath);
            //qDebug()<<"File:"<<fileInfo.absoluteFilePath().remove(list.at(0));
            writer->addFile(fileInfo.absoluteFilePath().remove(list.at(0)),file.readAll());
            file.close();
        }

    }
    return fileList;
}
void CompreDecompreFileThread::compression_file_run(QString srcPath, QString destPath)
{
    qDebug()<<QThread::currentThreadId();
    if(srcPath == nullptr || destPath == nullptr)
    {
        emit compression_res_signal(ResultE::failed,100,tr("路径为空!"));
        return;
    }
    QFileInfo fileDistInfo(destPath);
    if(fileDistInfo.isFile())   //目的路径不能为文件名
    {
        emit compression_res_signal(ResultE::failed,100,tr("路径不能为文件!"));
        return;
    }


    QFileInfo fileInfo(srcPath);
    if(fileInfo.isFile())//压缩的是一个文件
    {
        QString saveFileName = destPath+"/"+fileInfo.baseName()+".zip";
        qDebug()<<"saveFileName:"<<saveFileName;
        this->zipWriter = new QZipWriter(saveFileName);
        QFile file(srcPath);
        if(!file.open(QIODevice::ReadOnly))
        {
            emit compression_res_signal(ResultE::failed,100,tr("文件打开失败!"));
            return;
        }
        emit compression_res_signal(ResultE::running,50,tr("正在压缩中..."));
        this->zipWriter->addFile(file.fileName(),file.readAll());
        this->zipWriter->close();
        delete this->zipWriter;
        this->zipWriter = nullptr;
        emit compression_res_signal(ResultE::running,100,tr("正在压缩中..."));
        emit compression_res_signal(ResultE::success,100,tr("压缩完成!"));
    }
    else    //压缩的是一个文件夹
    {
        QString folderStr = srcPath.mid(srcPath.lastIndexOf("/")).remove("/");
        if(folderStr == nullptr)
        {
            emit compression_res_signal(ResultE::failed,100,tr("压缩文件路径错误!"));
            return;
        }
        emit compression_res_signal(ResultE::running,50,tr("正在压缩中..."));
        QString saveFileName = destPath+"/"+folderStr+".7z";
        qDebug()<<"saveFileName:"<<saveFileName;
        this->zipWriter = new QZipWriter(saveFileName);
        this->zipWriter->addDirectory(folderStr);
        this->ergodic_compression_file(this->zipWriter,folderStr,srcPath);
        delete this->zipWriter;
        this->zipWriter = nullptr;
        emit compression_res_signal(ResultE::running,100,tr("正在压缩中..."));
        emit compression_res_signal(ResultE::success,100,tr("压缩完成!"));
    }

}

void CompreDecompreFileThread::decompression_file_run(QString srcPathAndName, QString destPath)
{
    qDebug()<<QThread::currentThreadId();
    if(srcPathAndName == nullptr || destPath == nullptr)
    {
        emit decompression_res_signal(ResultE::failed,100,tr("路径为空!"));
        return;
    }
    QFileInfo destInfo(destPath);
    if(destInfo.isFile()||!destInfo.exists())
    {
        emit decompression_res_signal(ResultE::failed,100,tr("目的路径异常!"));
        return;
    }

    QFileInfo fileInfo(srcPathAndName);
    if(!fileInfo.isFile() || fileInfo.suffix() !="zip")
    {
        emit decompression_res_signal(ResultE::failed,100,tr("压缩文件为空!"));
        return;
    }
    emit decompression_res_signal(ResultE::running,50,tr("正在解压缩..."));
    this->zipReader = new QZipReader(srcPathAndName);
    bool res = this->zipReader->extractAll(destPath);
    emit decompression_res_signal(ResultE::running,100,tr("正在解压缩..."));
    if(res) //解压缩成功
    {
        emit decompression_res_signal(ResultE::success,100,tr("解压缩完成!"));
    }
    else
    {
         emit decompression_res_signal(ResultE::failed,100,tr("解压缩失败!"));
    }

    this->zipReader->close();
    delete this->zipReader;
    this->zipReader = nullptr;

}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "QtGui/private/qzipreader_p.h"
#include "QtGui/private/qzipwriter_p.h"

#include <QFileInfoList>
#include <QDir>
#include <QFile>

#include "compredecomprefilethread.h"

#include <QThread>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT
signals:
    void compress_signal(QString srcPath,QString destPath);
    void decompress_signal(QString srcPath,QString destPath);
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_btnZip_clicked();

    void on_btnUnZip_clicked();

    void compress_res_slot(CompreDecompreFileThread::ResultE res,quint8 progress,QString remarks = nullptr);
    void decompress_res_slot(CompreDecompreFileThread::ResultE res,quint8 progress,QString remarks = nullptr);

private:
    Ui::MainWindow *ui;
    CompreDecompreFileThread *compreDecompreFileThread;
    QThread *compreDecompreFileMainThread;

};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    compreDecompreFileThread = new CompreDecompreFileThread;
    compreDecompreFileMainThread = new QThread;

    compreDecompreFileThread->moveToThread(compreDecompreFileMainThread);
    compreDecompreFileMainThread->start();

    connect(this,&MainWindow::compress_signal,compreDecompreFileThread,&CompreDecompreFileThread::compression_file_run);
    connect(this,&MainWindow::decompress_signal,compreDecompreFileThread,&CompreDecompreFileThread::decompression_file_run);

    connect(compreDecompreFileThread,&CompreDecompreFileThread::compression_res_signal,this,&MainWindow::compress_res_slot);
    connect(compreDecompreFileThread,&CompreDecompreFileThread::decompression_res_signal,this,&MainWindow::decompress_res_slot);
    qDebug()<<QThread::currentThreadId();
}

MainWindow::~MainWindow()
{
    delete ui;
}


//bool zipReader(QString zipPath="test.zip", QString zipDir="")
//{
//    QDir tempDir;
//    if(!tempDir.exists(zipDir)) tempDir.mkpath(zipDir);
//    QZipReader reader(zipPath);
//    return reader.extractAll(zipDir);
//}

void MainWindow::on_btnZip_clicked()
{
    QString filePath = QApplication::applicationDirPath()+"/test";
    QString zipPath = QApplication::applicationDirPath();

    emit compress_signal(filePath,zipPath);

}


void MainWindow::on_btnUnZip_clicked()
{
    QString filePath = QApplication::applicationDirPath()+"/test.zip";
    QString zipPath = QApplication::applicationDirPath()+"/unTest";

    qDebug()<<"filePath:"<<filePath<<"zipPath:"<<zipPath;

    emit decompress_signal(filePath,zipPath);
}

void MainWindow::compress_res_slot(CompreDecompreFileThread::ResultE res, quint8 progress, QString remarks)
{
    qDebug()<<"Com:"<<"  res:"<<res<<"  progress:"<<progress<<"  remarks:"<<remarks;
}

void MainWindow::decompress_res_slot(CompreDecompreFileThread::ResultE res, quint8 progress, QString remarks)
{
    qDebug()<<"deCom:"<<"  res:"<<res<<"  progress:"<<progress<<"  remarks:"<<remarks;
}

mainwindow.ui

本文福利,费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QT嵌入式开发,Quick模块等等)↓↓↓↓↓↓见下面↓↓文章底部点击费领取↓↓

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/9488.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

控制游戏人物移动的细节到底有多少?

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! 本文由 秩沅 原创 收录于专栏 unity实战入门 在游戏中我们在做控制游戏物体移动时会碰到以下常见的几种情况&#xff1a; 文章目录在游戏中…

adb shell AT指令发送短信

开启两个&#xff0c;命令行窗口。都进入adb shell。 查看 /dev下的smd设备节点&#xff0c;选取一个进行读写操作 一个窗口用来进行读&#xff0c;另一个窗口进行写入指令操作&#xff0c;读取和写入的节点需要一致。 SH4-1:/ # ls /dev/smd* ls /dev/smd* /dev/smd11 /dev/…

隐式神经表示一:神经网络拟合图像Implicit Neural Representations with Periodic Activation Functions

文章目录1. Implicit Neural Representations with Periodic Activation Functions0. 什么是隐式神经表示1. 了解SineLayer的初始化&#xff0c;还是没了解。。。2. 均匀分布3. Lemma 1.14. 一个简单实验, 拟合图像4.1 网络模型代码如下&#xff0c;就是全连接网络&#xff0c;…

【自然语言处理(NLP)】基于BiLSTM+CRF的事件抽取

【自然语言处理&#xff08;NLP&#xff09;】基于BiLSTMCRF的事件抽取 作者简介&#xff1a;在校大学生一枚&#xff0c;华为云享专家&#xff0c;阿里云专家博主&#xff0c;腾云先锋&#xff08;TDP&#xff09;成员&#xff0c;云曦智划项目总负责人&#xff0c;全国高等学…

Centos 7 安装 wget

文章目录1. wget命令详解:2.查看帮助手册3.使用 wget 下载单个文件4.使用 wget -O 下载并以不同的文件名保存5.使用 wget -c 断点续传6.使用 wget -b 后台下载1. wget命令详解: wget是Linux中的一个下载文件的工具&#xff0c;wget是在Linux下开发的开放源代码的软件&#xff…

tomcat线程池-深度分析tomcat线程池设计与现实

1.概述 在正式进入Tomcat线程池之前&#xff0c;小伙伴们可以先回顾一下JDK中的线程池相关特性&#xff0c;对于JDK线程池的总结和源码的解析感兴趣的童鞋&#xff0c;也可参考博主的层层剖析线程池源码的这篇文章&#xff0c;文章主要讲述对线程池的生命周期&#xff0c;核心参…

五、事件系统-原生事件-react中的合成事件-详解事件的冒泡和捕获机制

目标 深入理解和掌握事件的冒泡及捕获机制理解react中的合成事件的本质在react组件中合理的使用原生事件 知识点 在原生的dom模型上触发的事件会进行事件传递。而所谓的事件传递指的是当在A元素上触发某一事件的时候&#xff0c;B元素如果满足了和A元素一定的关系的话&#xf…

freeswitch如何判断挂机方

概述 freeswitch作为VOIP的软交换平台&#xff0c;需要对呼叫的信息做判断和归类。 常见的呼叫信息中&#xff0c;挂机方向的信息对于话单统计有很大的用处。 但是fs的原始话单和日志中并没有挂机方向的信息。 环境 centos&#xff1a;CentOS7 freeswitch&#xff1a;v1.…

火遍国内外IT技术圈,豆瓣 9.7!这本技术书籍直接封神了

这是一本在国内外都被称为技术书籍巅峰之作的神书&#xff01; 国内的豆瓣评分 9.7&#xff08;满分 10.00&#xff09;&#xff0c;接近 90% 的人为这本书打了五星好评。 国外的 Goodreads&#xff08;类似于豆瓣&#xff09; 评分 4.72&#xff08;满分 5.00&#xff09; &a…

元宇宙:下一代互联网的“美丽新世界”

8月6日到8日,美国超人气歌手Ariana Grande在全球不同地区,连续举办了5场演唱会。与众不同的是,演出的举办地点在游戏《堡垒之夜》(Fortnite)中。全球上千万的玩家,使用自己的游戏角色盛装出席。演出中,一系列的小游戏贯穿了主线,最后粉丝在绚丽的场景中和“Ariana”一对…

42、Spring AMQP DirectExchange

1、DirectExchange 2、案例 3、通过配置类实现 1、配置类 2、Publisher 3、Consumer 4、测试结果 4、通过注解实现 1、Consumer添加Linstener 2、Publisher 执行测试方法 3、测试结果 4、总结分析 学习了DirectExchange之后&#xff0c;发现与FanoutExchange有些许差异&#…

腾讯程序员的手码K8S+Jenkins笔记

最近在GitHub上认识一个腾讯大佬&#xff0c;从他手上得到一份K8SJenkins笔记&#xff0c;好东西还是要共享的&#xff01;希望这份笔记能让你技术更上一层&#xff01; 从理论到实战深入K8S 学习K8S的学习笔记很少有比较齐全的&#xff0c;而这份K8S学习笔记&#xff0c;尽量…

谈了这么久的无代码到底是什么?

尽管我们一直在谈论关于“无代码”的方方面面&#xff0c;但却并没有专门谈及“无代码”是什么。不仅许多刚听到这个名词的人会感到疑惑&#xff0c;就算熟悉这一名词的可能也无法给出一个准确的定义&#xff0c;又或者常常将其与另一个相近的名词“低代码”弄混。 今天我们专…

Revit插件实现【快速扣减】的两种操作

翻模的过程中&#xff0c;我们在处理细节问题的时候&#xff0c;如果只是两个构件之间的重合&#xff0c;我们可以利用“连接”命令进行扣减。而如果是想让多个构件进行扣减操作&#xff0c;而不是整层或者整栋楼都按照同样的扣减顺序进行的话&#xff0c;我们可以利用橄榄山和…

Windows安全日志分析

Windows安全日志分析 0x00 引言 在应急响应初步阶段&#xff0c;我们会对系统日志、中间件安全日志、恶意文件等进行收集。接下来便是要进一步对这些文件进行分析&#xff1a;对恶意文件逆向、日志文件分析、梳理入侵时间线和入侵路径等。本文主要对Windows安全日志进行举例分…

Mybatis整合达梦数据库

陈老老老板&#x1f9b8;&#x1f468;‍&#x1f4bb;本文专栏&#xff1a;国产数据库-达梦数据库&#xff08;主要讲一些达梦数据库相关的内容&#xff09;&#x1f468;‍&#x1f4bb;本文简述&#xff1a;本文讲一下SpringBoot整合Mybatis与达梦数据库&#xff0c;就是简单…

全网最详细|Oracle12C安装和卸载图文教程

一. 数据库的引入 以前将数据用变量、数组、对象存在内存&#xff0c;而内存只能短暂存储数据。如果我们想长久存数据用文件将数据存在磁盘上&#xff0c;不方便存取和管理数据&#xff0c;因此可以使用数据库来存数据。 二. 数据库基础概念 2.1数据库(database,简称DB) 以…

QRegExpValidator(正则验证器)

QRegExpValidator QRegExpValidator 使用正则表达式 &#xff08;regexp&#xff09; 来确定输入字符串是可接受、中间还是无效的。正则表达式可以在构建 QRegExpValidator 时提供&#xff0c;也可以在以后提供。 构造函数&#xff1a; ​ 常用的函数&#xff1a; setRegE…

在Windows上使用Docker搭建ChirpStack私有LoRa服务端

在Windows上使用Docker容器部署ChirpStack服务&#xff0c;首先若要在Windows 10或11 上运行容器&#xff0c;需要以下条件&#xff1a; 一个运行 Windows 10 或 11 专业版或企业版的物理计算机系统。Hyper-V 功能已启用。 Windows下的Docker安装 1.Docker为Windows提供了一款…

如何设计一个支撑数亿用户的系统

要设计出一套能支撑几十亿人的系统是很困难的。对于软件架构师来说&#xff0c;这一直是一项很大的挑战&#xff0c;但是&#xff0c;从现在开始&#xff0c;看完我的文章&#xff0c;你就会觉得容易很多了。 下面是我在本文中提到的几个话题&#xff1a; 从最简单的开始&…