Quickest way to search a directory for files with a specified extension
-
@#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 -
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.