【问题标题】:Walk a directory recursively in Qt, skip the folders "." and ".."在 Qt 中递归遍历目录,跳过文件夹“。”和 ”..”
【发布时间】:2012-08-22 22:04:49
【问题描述】:

我在使用 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 也会返回 '.'和“..”目录。使用这种设置,这被证明是一个主要问题。

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

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

【问题讨论】:

    标签: c++ qt directory


    【解决方案1】:

    您应该尝试在entryInfoList 中使用QDir::NoDotAndDotDot 过滤器,如documentation 中所述。

    编辑

    【讨论】:

    • 是的,如here 所述,QT 需要为 QDir,Filter 需要用 QDir::AllEntries 扩展。您仍然得到“正确”,因为您为我指出了正确的方向。谢谢你:)
    猜你喜欢
    • 2011-12-24
    • 2012-10-05
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    相关资源
    最近更新 更多