在Qt中递归浏览目录,跳过文件夹"."并".."

Walk a directory recursively in Qt, skip the folders "." and ".."

本文关键字:文件夹 Qt 递归 浏览      更新时间:2023-10-16

我在使用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.
        }
    }
}

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

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

我想做这件漂亮而时尚的事,有什么办法吗,我不知道?或者是唯一的方法,我得到一个普通的文件名(没有路径),并根据"进行检查和"…"?

您应该尝试在entryInfoList中使用QDir::NoDotAndDotDot筛选器,如文档中所述。

编辑

  • 不要忘记添加QDir::FilesQDir::DirsQDir::AllFiles来获取文件和/或目录,如本文所述。

  • 您可能还想检查一下前面的问题。