Program crash when iterating over dirs with recursion
-
Good evening,
I probably do something stupid but: I need to scan the folder of users' choice, for which I get absolute path, for certain files. Recursively.
So I wrote simple routine:QStringList FileClass::scanFiles(const QString &path) const { if (path.isEmpty()) { return QStringList(); } QDir dir(path); QFileInfoList infos = dir.entryInfoList(QStringList(),QDir::Dirs|QDir::NoDotAndDotDot|QDir::Readable); QStringList retval; if (infos.size()>0) { for (auto x=0;x<infos.size();++x) { retval.append(scanFiles(infos.at(x).absolutePath())); } } infos = dir.entryInfoList(extensions,QDir::Files|QDir::NoDotAndDotDot|QDir::Readable); if (infos.size()>0) { for (auto x=0;x<infos.size();++x) { retval.append(infos.at(x).absoluteFilePath()); } } return retval; }
extensions
here is simple QStringList with five or six items.
Now, when I do employ this routine the program crashes without any message even if the tree is like two folders deep and has total of less than 100 files.
Does anyone has an idea what error I made?
Qt 6.2.3, macOS. -
Hi,
Isn't QDirIterator what you are looking for ?
-
@artwaw said in Program crash when iterating over dirs with recursion:
Now, when I do employ this routine the program crashes without any message
The first thing I would do is
qDebug() << path
as line #1 in the method :)But @SGaist's
QDirIterator
is already written for you. -
@artwaw said in Program crash when iterating over dirs with recursion:
retval.append(scanFiles(infos.at(x).absolutePath()));
QFileInfo::absolutePath() const
Returns a file's path absolute path. This doesn't include the file name.hence an infinite loop :)
As said by others QDirIterator is the way to go.
-
Ok, that was one of my less stellar moments, I somehow overlooked to check for repeated paths...
Also, I was absolutely oblivious to the existence of QDirIterator! HOW. Thank you @SGaist
@mpergand The idea was to first recurrently check for existing folders and dive into them to the very bottom, hence path() without the filename was what I needed. Once the routine is out of folders it was supposed to get the file paths - again, idea was that the list is already sorted from the deepest point and ends up with the top-level files.
The idea is moot since I was indeed trying (and failing) to reinvent the wheel.Thank you all for pointing out my mistakes but I will mark @SGaist's post as the solution, as he provided me with (Yet Another Useful Class) what I will use.
Thank you!