c++qtglobqtcoreqdir

List files in sub-directories with QDir's filter


I'm looking for a function similar to the python glob function.

If my folder structure is:
folder1/abc1.txt
folder1/xyz1.txt
folder1/abc2.txt
folder2/abc3.txt
folder2/xyz4.txt
folder3/abc5.txt

then if I give */abc*, I'm looking for an output of:

folder1/abc1.txt
folder1/abc2.txt
folder2/abc3.txt
folder3/abc5.txt

I tried entrylist, but it just lets me filter on what's in the current folder.


Solution

  • You can of course traverse recursively with an embedded loop like this:

    main.cpp

    #include <QDir>
    #include <QFileInfoList>
    #include <QString>
    #include <QStringList>
    #include <QDebug>
    
    void traverse(const QString &pattern, const QString &dirname, int level)
    {
        QDir dir(dirname);
        dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoSymLinks | QDir::NoDot | QDir::NoDotDot);
    
        static const QStringList stringList = pattern.split('/');
        foreach (QFileInfo fileInfo, dir.entryInfoList(stringList.mid(level, 1))) {
            if (fileInfo.isDir() && fileInfo.isReadable())
                traverse(pattern, fileInfo.filePath(), level+1);
            else if (stringList.size() == (level + 1))
                qDebug() << fileInfo.filePath();
        }
    }
    
    int main()
    {
        traverse("*/abc*", ".", 0);
        return 0;
    }
    

    main.pro

    TEMPLATE = app
    TARGET = main
    QT = core
    SOURCES += main.cpp
    

    Build and Run

    qmake && make && ./main
    

    Output

    "./folder1/abc1.txt"
    "./folder1/abc2.txt"
    "./folder2/abc3.txt"
    "./folder3/abc5.txt"