我遇到了一些问题,使用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也会返回'.'和'..'目录。 这种设置会带来重大问题。
进入'.'时,它会两次或者甚至无限次(因为'.'始终是第一个元素)遍历整个目录。而使用'..'则会重新对父目录下的所有文件夹执行此过程。
我想要做到好看且流畅,有没有任何方法可以达成这个目的?还是唯一的方法是获取纯文件名(不包括路径)并将其与'.'和'..'进行比较?