您当然可以使用这样的嵌入式循环递归遍历:
主文件
#include <QDir>
#include <QFileInfoList>
#include <QString>
#include <QStringList>
#include <QDebug>
void traverse(const QString &pattern, const QString &dirname, int level)
{
QDir dir(dirname);
dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoSymLinks | QDir::NoDot | QDir::NoDotDot);
static const QStringList stringList = pattern.split('/');
foreach (QFileInfo fileInfo, dir.entryInfoList(stringList.mid(level, 1))) {
if (fileInfo.isDir() && fileInfo.isReadable())
traverse(pattern, fileInfo.filePath(), level+1);
else if (stringList.size() == (level + 1))
qDebug() << fileInfo.filePath();
}
}
int main()
{
traverse("*/abc*", ".", 0);
return 0;
}
主程序
TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp
构建并运行
qmake && make && ./main
输出
"./folder1/abc1.txt"
"./folder1/abc2.txt"
"./folder2/abc3.txt"
"./folder3/abc5.txt"