【发布时间】: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 也会返回 '.'和“..”目录。使用这种设置,这被证明是一个主要问题。
通过进入'.',它将遍历整个目录两次,甚至无限次(因为'.'始终是第一个元素),使用'..'它将为父级下的所有文件夹重做该过程目录。
我想做得又漂亮又时尚,有什么办法可以解决这个问题,我不知道吗?或者是唯一的方法,我得到纯文件名(没有路径)并对照'。'检查它。和'..'?
【问题讨论】: