Posted by: developer | May 18, 2011

Recursively remove a directory in Qt4

Today I wrote a code to remove a directory and all its sub-directories and files.

bool MyUtil::removeDir(const QString& dirName)
    bool result = true;
    QDir dir(dirName);

    if (dir.exists(dirName))
        Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot|QDir::AllDirs|QDir::Files, QDir::DirsFirst))
            if (info.isDir())
                result = removeDir(info.absoluteFilePath());
                result = QFile::remove(info.absoluteFilePath());

            if (!result)
                return result;
        result = dir.rmdir(dirName);
        QFile file(dirName);
        if (file.exists())
            result = file.remove();

    return result;



  1. Note: Qt5 will have QTemporaryDir, including a similar removeDir method. I’m just finishing the last fixes on it.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


%d bloggers like this: