qt 解压压缩包demo
时间: 2023-07-05 10:08:25 浏览: 91
以下是一个使用 Qt 的 QZipReader 和 QZipWriter 类进行解压和压缩的示例代码:
```cpp
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QZipReader>
#include <QZipWriter>
void unzip(const QString& zipFilePath, const QString& destinationFolderPath)
{
// 创建 ZipReader 对象
QZipReader zipReader(zipFilePath);
if (!zipReader.isOpen())
{
qWarning() << "Failed to open zip file:" << zipFilePath;
return;
}
// 遍历 zip 文件中的所有条目
for (const QString& fileName : zipReader.fileNames())
{
QZipReader::FileInfo fileInfo = zipReader.entryInfo(fileName);
// 如果是文件夹,则创建对应的目录
if (fileInfo.isDir())
{
QString dirPath = destinationFolderPath + "/" + fileName;
QDir().mkpath(dirPath);
}
else // 如果是文件,则解压到对应的文件路径
{
QString filePath = destinationFolderPath + "/" + fileName;
QFile file(filePath);
if (!file.open(QIODevice::WriteOnly))
{
qWarning() << "Failed to open file for writing:" << filePath;
continue;
}
if (!zipReader.extractFile(fileName, &file))
{
qWarning() << "Failed to extract file:" << fileName;
continue;
}
file.close();
}
}
}
void zip(const QString& sourceFolderPath, const QString& zipFilePath)
{
// 创建 ZipWriter 对象
QZipWriter zipWriter(zipFilePath);
if (!zipWriter.isOpen())
{
qWarning() << "Failed to create zip file:" << zipFilePath;
return;
}
// 遍历源文件夹中的所有文件和子文件夹,并将它们添加到 zip 文件中
QDirIterator it(sourceFolderPath, QDirIterator::Subdirectories);
while (it.hasNext())
{
QString filePath = it.next();
QFileInfo fileInfo(filePath);
if (fileInfo.isDir())
{
zipWriter.addDirectory(filePath.mid(sourceFolderPath.length() + 1));
}
else
{
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly))
{
qWarning() << "Failed to open file for reading:" << filePath;
continue;
}
if (!zipWriter.addFile(filePath.mid(sourceFolderPath.length() + 1), &file))
{
qWarning() << "Failed to add file to zip:" << filePath;
continue;
}
file.close();
}
}
zipWriter.close();
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
// 解压 zip 文件
QString zipFilePath = "test.zip";
QString destinationFolderPath = "test";
unzip(zipFilePath, destinationFolderPath);
// 压缩文件夹
QString sourceFolderPath = "test";
QString newZipFilePath = "new.zip";
zip(sourceFolderPath, newZipFilePath);
return app.exec();
}
```
上述代码中,unzip 函数使用 QZipReader 类从 zip 文件中解压条目,zip 函数使用 QZipWriter 类将文件夹压缩为 zip 文件。这两个函数都需要传入相应的文件路径参数。
阅读全文