qt中实现压缩文件夹功能

1.将kuba zip引入到你的项目中。
在git hub中有介绍

2…h文件
#include <3rd_lib/zip/zip.h>

private:
 QString m_file_path;//指定的存储压缩包的文件夹
  QString m_resources="./resource_file";//被存储的文件夹
 public:
 //
 QString compressFolder(const QString &folderPath, const QString &zipFilePath);
   void zip_walk(struct zip_t *zip, const QString &folderPath);

3.。cpp文件

QString Backuppage:: compressFolder(const QString &folderPath, const QString &zipFilePath) {
    QString str;
    QDir dir(zipFilePath);
    if (!dir.exists()) {
        str="Error: Folder does not exist!";
    }else{
        QDateTime currentDateTime = QDateTime::currentDateTime();
        // 格式化日期时间为字符串,去除年月日和时分秒之间的空格
        QString formattedDateTime = currentDateTime.toString("yyyy-MM-ddhh:mm:ss");
        QString nowFile=zipFilePath+formattedDateTime+".zip";
        QByteArray byteArray = nowFile.toUtf8();
        const char *filePath = byteArray.constData();
         struct zip_t * zip=zip_open(filePath, ZIP_DEFAULT_COMPRESSION_LEVEL,'w');
         zip_walk(zip,zipFilePath);
        zip_close(zip);
            QString destinationFilePath = QDir(folderPath).filePath(QFileInfo(nowFile).fileName());
            if (!QFile::rename(nowFile, destinationFilePath)) {
                str = "Error: Failed to move compressed file to destination folder.";
            } else {
               str = "备份成功!";
            }

    }

    return str;;
}

//递归压缩文件夹中的所有内容

void Backuppage::zip_walk(struct zip_t *zip,const QString &folderPath) {
    QDir dir(folderPath);
    QFileInfoList list = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs);
    QString absolutePath = QDir::current().absolutePath();
    qDebug()<<"absolutePath="<<absolutePath;
    foreach (QFileInfo fileInfo, list) {
        QString filePath = fileInfo.absoluteFilePath();
        if (fileInfo.isDir()) {
            // Recursively process directories
            zip_walk(zip, filePath);
        } else {
            // Process files
            QString relativePath = QDir(absolutePath).relativeFilePath(filePath);
            const char *file  = relativePath.toUtf8().constData();
            zip_entry_open(zip, file);
            zip_entry_fwrite(zip, file);
            zip_entry_close(zip);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值