Has anyone seen QDirIterator?
Recently QDirIterator showed up in the Qt 4.3 snapshots. Doesn’t have that many bells and whistles, but it’s a pretty useful tool. Here’s how to use it:
QDirIterator it("testDir/");
while (it.hasNext()) {
qDebug() < < it.next();
// "testDir/."
// "testDir/.."
// "testDir/directory"
// "testDir/file.txt"
// "testDir/otherFile.txt"
// "testDir/otherDirectory"
// "testDir/symlink"
// ...
}
It provides a convenient way of stepping through all entries in a directory. Much like QDir::entryList(), but it’s different in two areas:
-
It’s an iterator, giving you one entry at a time, and the first entry is available immediately. That means it scales much better than QDir::entryList(), which loads all entries in a directory into memory at once, before the results are available. (For very large directories, that can take some time, and it allocates memory.)
-
It supports subdirectory recursion, and following symlinks. Take the above example, and add a flag:
QDirIterator it("/home/ahanssen", QDirIterator::Subdirectories);
while (it.hasNext()) {
qDebug() < < it.next();
// "testDir/."
// "testDir/.."
// "testDir/directory"
// "testDir/directory/."
// "testDir/directory/.."
// "testDir/directory/fileInDirectory.txt"
// "testDir/directory/dirInDirectory/otherfile.txt"
// "testDir/file.txt"
}
Now you don’t need to write recursive functions to do operations on all entries in a directory. If you add QDirIterator::FollowSymlinks, it will recurse into symlinked directories too (it even resolves shortcuts on Windows). And it skips symlink loops (link -> “.” or link -> “..” and so on).
I don’t know about you but… I think it’s a neat class :-).
The fun part is when you run this thing on UNC shares on Windows, or against local Qt resources. Iterate over “:/”, for example, adding the subdirectory flag, and see for yourself. :-)