void MainWindow::zipFile(QFileInfo fileInfo, QString passwd)
{
QString zipPath = fileInfo.filePath().left(fileInfo.filePath().indexOf('.')) + QString(".zip");
QString password(passwd);
QuaZip newZip(zipPath); // 将要打包生成的zip包
if(newZip.open(QuaZip::mdCreate)) {
QuaZipFile zipFile(&newZip); // 压缩包内的文件
QuaZipNewInfo newInfo(fileInfo.fileName(), fileInfo.dir().path());
if(zipFile.open(QIODevice::WriteOnly, newInfo, password.toUtf8().constData(), 0, 8)) {
QFile file(fileInfo.filePath());
if(file.open(QIODevice::ReadOnly)) {
zipFile.write(file.readAll());
} else {
qDebug() << "<file not found." << _INFO_STR_ << ">";
}
file.close();
zipFile.close();
} else {
qDebug() << "<zipFile open failed." << _INFO_STR_ << ">";
}
} else {
qDebug() << "newZip open failed." << _INFO_STR_ << ">";
}
newZip.close();
}
// 调用函数
QFileInfo info(QString("C:\\Users\\XingWei\\Documents\\untitled33\\DetechThread.h"));
zipFile(info, "123456");
此时看到已经生成了zip包,如下图所示。
通过测试压缩包的正确性,我采用了不同的解压工具进行测试,解压结果如下:
解压工具 | 是否正确解压 |
---|---|
WinRAR | 是 |
Bandizip | 是 |
Windows资源管理器 | 是 |
360解压 | 否 |
7-Zip | 否 |
好压 | 否 |
怎么回事呢,有的行,有的不行。。
就只是打包压缩了一个文件而已,按理说,要么这些工具都可以解出来,要么都不行
。
解决方案,为了能够适配所有解压工具,只是在上述代码中做一处更改即可。
// 将上述中的
QuaZipNewInfo newInfo(fileInfo.fileName(), fileInfo.dir().path());
// 更改为
QuaZipNewInfo newInfo(fileInfo.fileName(), fileInfo.filePath());
对,就这样,一切便解决了。。。
版权声明:本文为TianYanRen111原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。