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);
}
}
}