Quickest way to search a directory for files with a specified extension



  • What would be the quickest way to search a directory for files with a specified extension (ie. ¨.txt¨)? Any help appreciated! This should include any subdirectories as well.



  • @#include <QtDebug>

    QDirIterator dirIt("/folder_path",QDirIterator::Subdirectories);
    while (dirIt.hasNext()) {
    dirIt.next();
    if (QFileInfo(dirIt.filePath()).isFile())
    if (QFileInfo(dirIt.filePath()).suffix() == "txt")
    qDebug()<<dirIt.filePath();
    }@



  • ... or more simply "QDir::entryList":http://doc.qt.nokia.com/stable/qdir.html#entryList

    In your case :

    @
    QStringList nameFilter("*.txt");
    QDir directory(your_path);
    QStringList txtFilesAndDirectories = directory.entryList(nameFilter);
    @



  • [quote author="cincirin" date="1319612618"]... or more simply[/quote]
    but not recursive



  • [quote author="RazrFalcon" date="1319612980"]but not recursive[/quote]

    Truth in, but @phamtv not said he wants recursive.
    I understand he wants all subdirectories from a given directory. :-)



  • You can easily make this a recursive method. Use "QDir::entryInfoList() ":http://doc.qt.nokia.com/4.7/qdir.html#entryInfoList, you get the info whether an entry is a directory from [[Doc:QFileInfo]].



  • I would make a recursive method that combines cincirin's method of listing the actual files with a recursive approach to get the subdirectories of the current directory, and do the same for each of those subdirectories.

    One thing about recursive methods like these:
    I foudn that it is convenient to wrap them in a non-recursive method. That method is then the API, the recursive one is an implementation detail that needs to be private. The reason is that often the method signature that you need for the recursive function is not optimal for the API of your class. It exposes too much internals of the recursive nature of the function. Though, I guess, you can do without in this case.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.