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

前端 未结 4 1366
醉梦人生
醉梦人生 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:28

    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

    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.

    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

提交回复
热议问题