Recursively iterate over all the files in a directory and its subdirectories in Qt

前端 未结 4 1369
醉梦人生
醉梦人生 2020-12-07 15:47

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?

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 16:23

    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.

提交回复
热议问题