ATaylor
ATaylor

Reputation: 2598

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

I have a little trouble using the Qt functions to walk through a directory recursively. What I'm trying to do:

Open a specified directory. Walk through the directory, and each time it encounters another directory, open that directory, walk through the files, etc.

Now, how I am going about this:

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.
        }
    }
}

Now, the actual problem I'm facing: Naturally, entryInfoList would also return the '.' and '..' directories. With this setup, this proves a major problem.

By going into '.', it would go through the entire directory twice, or even infinitely (because '.' is always the first element), with '..' it would redo the process for all folders beneath the parent directory.

I would like to do this nice and sleek, is there any way to go about this, I am not aware of? Or is the only way, that I get the plain filename (without the path) and check that against '.' and '..'?

Upvotes: 8

Views: 8085

Answers (1)

Pierre GM
Pierre GM

Reputation: 20339

You should try to use the QDir::NoDotAndDotDot filter in your entryInfoList, as described in the documentation.

EDIT

  • Don't forget to add a QDir::Files, or QDir::Dirs or QDir::AllFiles to pick up the files and/or directories, as described in this post.

  • You may also want to check this previous question.

Upvotes: 13

Related Questions