如何在Qt C++中用Quazip不解压获取压缩包内父目录数量?
用Quazip不解压统计压缩包内父目录数量
完全可以通过Quazip实现,无需解压压缩包。核心思路是遍历压缩包内所有条目,解析每个条目的路径,提取并去重所有父目录,最后统计唯一父目录的数量。
实现步骤与代码示例
- 打开目标压缩包,初始化Quazip实例
- 遍历压缩包内所有文件/目录条目
- 解析每个条目的路径,提取对应的父目录
- 用集合存储唯一父目录,避免重复统计
- 返回集合的大小即为父目录数量
#include <quazip/quazip.h> #include <quazip/quazipfileinfo.h> #include <QSet> #include <QString> #include <QDebug> int countUniqueParentDirs(const QString& zipFilePath) { QuaZip zip(zipFilePath); if (!zip.open(QuaZip::mdUnzip)) { qWarning() << "打开压缩包失败:" << zip.getZipError(); return -1; } QSet<QString> uniqueParentDirs; QuaZipFileInfo entryInfo; // 遍历所有压缩条目 for (bool hasNext = zip.goToFirstFile(); hasNext; hasNext = zip.goToNextFile()) { if (!zip.getCurrentFileInfo(&entryInfo)) { qWarning() << "获取条目信息失败"; continue; } QString entryPath = entryInfo.name; // 统一路径分隔符为/ entryPath.replace('\\', '/'); if (entryPath.endsWith('/')) { // 处理目录条目:取当前目录的父目录 int lastSlashPos = entryPath.lastIndexOf('/', entryPath.length() - 2); if (lastSlashPos != -1) { QString parentDir = entryPath.left(lastSlashPos + 1); uniqueParentDirs.insert(parentDir); } } else { // 处理文件条目:取文件所在的父目录 int lastSlashPos = entryPath.lastIndexOf('/'); if (lastSlashPos != -1) { QString parentDir = entryPath.left(lastSlashPos + 1); uniqueParentDirs.insert(parentDir); } // 根目录下的文件无父目录,跳过统计 } } zip.close(); return uniqueParentDirs.size(); }
关键细节说明
- 去重处理:使用
QSet存储父目录,自动过滤重复项,确保统计的是唯一父目录数量 - 路径兼容:统一将
\替换为/,适配不同系统下的压缩包路径格式 - 异常处理:包含压缩包打开失败、条目信息获取失败的错误提示,避免程序崩溃
- 边界情况:根目录下的文件/目录没有父目录,不会计入统计结果
使用示例
在Qt代码中调用该函数即可:
int parentDirCount = countUniqueParentDirs("path/to/your/file.zip"); if (parentDirCount != -1) { qDebug() << "压缩包内父目录数量:" << parentDirCount; }
内容的提问来源于stack exchange,提问作者qwertyuiop
相关产品推荐
相关产品推荐

