C++ 在Qt中递归迭代目录及其子目录中的所有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8052460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:55:43  来源:igfitidea点击:

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

c++qt

提问by Dimse

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?

我想递归扫描目录及其所有子目录以查找具有给定扩展名的文件 - 例如,所有 *.jpg 文件。你怎么能在 Qt 中做到这一点?

回答by Luca Carlon

I suggest you have a look at QDirIterator.

我建议你看看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.

您可以简单地递归使用QDir::entryList(),但 QDirIterator 更简单。此外,如果您碰巧有包含大量文件的目录,您会从 QDir::entryList() 获得相当大的列表,这在小型嵌入式设备上可能不太好。

回答by pnezis

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:

与您的代码的区别如下:

  • Breadth first search instead of depth first search (no reason for it, I just prefer it)
  • More filters in order to avoid sym links
  • EntryList instead of EntryInfoList. You don t need if you just want the name of the file.
  • 广度优先搜索而不是深度优先搜索(没有理由,我只是喜欢它)
  • 更多过滤器以避免符号链接
  • EntryList 而不是 EntryInfoList。如果您只想要文件的名称,则不需要。

I tested it and it works correctly, but notice the following:

我测试了它并且它工作正常,但请注意以下几点:

  • This may take a lot of time, so consider running it from thread
  • If there is deep recursion you may have problem with your stack
  • 这可能需要很多时间,所以考虑从线程运行它
  • 如果存在深度递归,您的堆栈可能有问题

回答by Paul-Sebastian Manole

I used QDirIterator.

我使用了 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):

这是我的做法,以及以非常快的速度递归查找所有 XML 绝对文件路径是多么简单(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.

编辑:我可能省略了一些声明,请注意。

回答by MangoCat

Another sample which indexes all files, using QFileInfo:

另一个使用 QFileInfo 索引所有文件的示例:

void ID3Tab::scanDir( QDir dir )
{ QFileInfoList fil = dir.entryInfoList( QStringList( "*.mp3" ),
                                         QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks,
                                         QDir::Name | QDir::IgnoreCase );
  foreach ( QFileInfo fi, fil )
    indexFile( fi );

  QFileInfoList dil = dir.entryInfoList( QStringList( "*" ),
                                         QDir::AllDirs | QDir::NoDotAndDotDot | QDir::NoSymLinks,
                                         QDir::Name | QDir::IgnoreCase );
  foreach ( QFileInfo di, dil )
    scanDir( QDir( di.absoluteFilePath() ) );
}