Quickest way to search a directory for files with a specified extension
-
wrote on 25 Oct 2011, 20:14 last edited by
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.
-
wrote on 25 Oct 2011, 20:47 last edited by
@#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();
}@ -
wrote on 26 Oct 2011, 07:03 last edited by
... 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);
@ -
wrote on 26 Oct 2011, 07:09 last edited by
[quote author="cincirin" date="1319612618"]... or more simply[/quote]
but not recursive -
wrote on 27 Oct 2011, 22:38 last edited by
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]].
-
wrote on 28 Oct 2011, 08:44 last edited by
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.
4/7