首页 > 解决方案 > 为什么删除所有内容后不删除父目录?

问题描述

我想通过 Qt 功能实现一个功能,该功能类似于QDir::removeRecursively()并删除一个目录,包括其文件和子目录。问题是该函数成功删除了所有包含文件,即使在子目录中,但不会删除父目录。

void removeDirectory(const QString &path)
{
    QDir directory(path);
    if(!directory.exists())
        throw QString("The directory does not exist.");

    QFileInfoList entries = directory.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries);
    for(QFileInfoList::const_iterator counter = entries.cbegin(); counter != entries.cend(); ++counter)
    {
        if(counter->isDir())
            removeDirectory(counter->absoluteFilePath());
        else
        {
            if(!QFile::remove(counter->absoluteFilePath()))
                throw QString(counter->absoluteFilePath() + " is not removed.");
            else
                qDebug() << counter->absoluteFilePath() << " is removed.";
        }
    }
    if(directory.rmdir("."))
       qDebug() << directory.absolutePath() << " is removed.";
    else
       qDebug() << directory.absolutePath() << " is failed to remove.";
}

我想问题出directory.rmdir(".")在我告诉程序删除当前目录的地方,但是这个操作失败了,因此目录本身没有被删除,尽管它是空的。

那么,为什么会发生这种情况,以及如何解决这个问题?

标签: c++qtrecursiondelete-directory

解决方案


推荐阅读