From 1bb51cb8b1de3ac795d408757812fc57fbf0a902 Mon Sep 17 00:00:00 2001 From: David Faure Date: Fri, 2 Dec 2011 10:39:19 +0100 Subject: Implement QDir::removeRecursively Task-number: QTBUG-4592 Change-Id: I363e2c24d1c0ada975b8b927d7c6e776b8aae579 Reviewed-by: Oswald Buddenhagen --- src/corelib/io/qdir.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ src/corelib/io/qdir.h | 2 ++ 2 files changed, 48 insertions(+) (limited to 'src/corelib/io') diff --git a/src/corelib/io/qdir.cpp b/src/corelib/io/qdir.cpp index 32fd81981b..44992fcd14 100644 --- a/src/corelib/io/qdir.cpp +++ b/src/corelib/io/qdir.cpp @@ -1470,6 +1470,52 @@ bool QDir::rmpath(const QString &dirPath) const return d->fileEngine->rmdir(fn, true); } +/*! + Removes the directory, including all its contents. + + Returns true if successful, otherwise false. + + If a file or directory cannot be removed, removeRecursively() keeps going + and attempts to delete as many files and sub-directories as possible, + then returns false. + + If the directory was already removed, the method returns true + (expected result already reached). + + Note: this function is meant for removing a small application-internal + directory (such as a temporary directory), but not user-visible + directories. For user-visible operations, it is rather recommended + to report errors more precisely to the user, to offer solutions + in case of errors, to show progress during the deletion since it + could take several minutes, etc. +*/ +bool QDir::removeRecursively() +{ + if (!d_ptr->exists()) + return true; + + bool success = true; + const QString dirPath = path(); + // not empty -- we must empty it first + QDirIterator di(dirPath, QDir::AllEntries | QDir::Hidden | QDir::System | QDir::NoDotAndDotDot); + while (di.hasNext()) { + di.next(); + const QFileInfo& fi = di.fileInfo(); + bool ok; + if (fi.isDir()) + ok = QDir(di.filePath()).removeRecursively(); // recursive + else + ok = QFile::remove(di.filePath()); + if (!ok) + success = false; + } + + if (success) + success = rmdir(absolutePath()); + + return success; +} + /*! Returns true if the directory is readable \e and we can open files by name; otherwise returns false. diff --git a/src/corelib/io/qdir.h b/src/corelib/io/qdir.h index 822173dfc8..e246f2f1aa 100644 --- a/src/corelib/io/qdir.h +++ b/src/corelib/io/qdir.h @@ -166,6 +166,8 @@ public: bool mkpath(const QString &dirPath) const; bool rmpath(const QString &dirPath) const; + bool removeRecursively(); + bool isReadable() const; bool exists() const; bool isRoot() const; -- cgit v1.2.3