I want to recursively scan a directory and all its sub-directories for files with a given extension - for example, all *.jpg files. How can you do that in Qt?
I used QDirIterator.
Here's how I do it and how simple it was to find all XML absolute file paths recursively very fast (Qt4.8.1):
// used to store the file paths
filesStack = new QStack();
// I use a file dialog to let the user choose the root folder to search in
if (fileDialog->exec() == QFileDialog::Accepted) {
QDir selectedDir(fileDialog->selectedFiles().first());
selectedDir.setFilter(QDir::Files |
QDir::Dirs | QDir::NoDot | QDir::NoDotDot);
QStringList qsl; qsl.append("*.xml"); // I only want XML files
selectedDir.setNameFilters(qsl);
findFilesRecursively(selectedDir);
}
// this function stores the absolute paths of each file in a QVector
void findFilesRecursively(QDir rootDir) {
QDirIterator it(rootDir, QDirIterator::Subdirectories);
while(it.hasNext()) {
filesStack->push(it.next());
}
}
Thanks to everyone for the hints.
EDIT: I may have omitted some declarations, beware.