在Qt中递归遍历目录,跳过文件夹"." 和"......"

ATa*_*lor 8 c++ directory qt

我在使用Qt函数递归遍历目录时遇到了一些麻烦.我正在做的事情:

打开指定的目录.遍历目录,每次遇到另一个目录时,打开该目录,浏览文件等.

现在,我如何做到这一点:

QString dir = QFileDialog::getExistingDirectory(this, "Select directory");
if(!dir.isNull()) {
    ReadDir(dir);
}

void Mainwindow::ReadDir(QString path) {
    QDir dir(path);                            //Opens the path
    QFileInfoList files = dir.entryInfoList(); //Gets the file information
    foreach(const QFileInfo &fi, files) {      //Loops through the found files.
        QString Path = fi.absoluteFilePath();  //Gets the absolute file path
        if(fi.isDir()) ReadDir(Path);          //Recursively goes through all the directories.
        else {
            //Do stuff with the found file.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我面临的实际问题:自然,entryInfoList也会返回'.' 和'..'目录.通过这种设置,这证明是一个主要问题.

通过进入'.',它将遍历整个目录两次,甚至是无限的(因为'.'始终是第一个元素),使用'..'它将重做父目录下所有文件夹的进程.

我想做的很好,很时尚,有什么办法可以解决这个问题,我不知道吗?或者是唯一的方法,我得到纯文件名(没有路径)并检查对'.' 和'..'?

Pie*_* GM 13

您应该尝试使用QDir::NoDotAndDotDot过滤器entryInfoList,如文档中所述.

编辑