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 suggest you have a look at QDirIterator.
QDirIterator it(dir, QStringList() << "*.jpg", QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext())
qDebug() << it.next();
You could simply use QDir::entryList() recursively, but QDirIterator is simpler. Also, if you happen to have directories with a huge amount of files, you'd get pretty large lists from QDir::entryList(), which may not be good on small embedded devices.
Example (dir is QDir::currentPath()):
luca @ ~/it_test - [] $ tree
.
├── dir1
│ ├── image2.jpg
│ └── image3.jpg
├── dir2
│ └── image4.png
├── dir3
│ └── image5.jpg
└── image1.jpg
3 directories, 5 files
luca @ ~/it_test - [] $ /path/to/app
"/home/luca/it_test/image1.jpg"
"/home/luca/it_test/dir3/image5.jpg"
"/home/luca/it_test/dir1/image2.jpg"
"/home/luca/it_test/dir1/image3.jpg"
This should work :
void scanDir(QDir dir)
{
dir.setNameFilters(QStringList("*.nut"));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
qDebug() << "Scanning: " << dir.path();
QStringList fileList = dir.entryList();
for (int i=0; i<fileList.count(); i++)
{
if(fileList[i] != "main.nut" &&
fileList[i] != "info.nut")
{
qDebug() << "Found file: " << fileList[i];
}
}
dir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
QStringList dirList = dir.entryList();
for (int i=0; i<dirList.size(); ++i)
{
QString newPath = QString("%1/%2").arg(dir.absolutePath()).arg(dirList.at(i));
scanDir(QDir(newPath));
}
}
The differences from your code are the following:
I tested it and it works correctly, but notice the following:
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<QString>();
// 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With