Introduce QDir::isEmpty()

A directory is empty when it doesn't contain files or folders.
We can exploit QDirIterator::hasNext() to check whether this is the
case. This is efficient since it doesn't list the whole folder (in the
non-empty case).

Test cases are added for both the empty and non-empty cases.

Change-Id: I0f7e26782c0f97f9c16f928dab6cae37927875d8
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
Elvis Angelaccio 2016-09-12 18:48:17 +02:00
parent 5311d481c2
commit 3f455a4b53
3 changed files with 45 additions and 0 deletions

View File

@ -1842,6 +1842,26 @@ bool QDir::exists(const QString &name) const
return QFile::exists(filePath(name));
}
/*!
Returns whether the directory is empty.
Equivalent to \c{count() == 0} with filters
\c{QDir::AllEntries | QDir::NoDotAndDotDot}, but faster as it just checks
whether the directory contains at least one entry.
\note Unless you set the \p filters flags to include \c{QDir::NoDotAndDotDot}
(as the default value does), no directory is empty.
\sa count(), entryList(), setFilter()
\since 5.9
*/
bool QDir::isEmpty(Filters filters) const
{
const auto d = d_ptr.constData();
QDirIterator it(d->dirEntry.filePath(), d->nameFilters, filters);
return !it.hasNext();
}
/*!
Returns a list of the root directories on this system.

View File

@ -144,6 +144,8 @@ public:
void setSorting(SortFlags sort);
uint count() const;
bool isEmpty(Filters filters = Filters(AllEntries | NoDotAndDotDot)) const;
QString operator[](int) const;
static QStringList nameFiltersFromString(const QString &nameFilter);

View File

@ -211,6 +211,9 @@ private slots:
void cdBelowRoot_data();
void cdBelowRoot();
void emptyDir();
void nonEmptyDir();
private:
#ifdef BUILTIN_TESTDATA
QString m_dataPath;
@ -2281,6 +2284,26 @@ void tst_QDir::cdBelowRoot()
QCOMPARE(dir.path(), rootPath);
}
void tst_QDir::emptyDir()
{
const QString tempDir = QDir::currentPath() + "/tmpdir/";
QVERIFY(QDir().mkdir(tempDir));
QVERIFY(QDir(tempDir).mkdir("emptyDirectory"));
QDir testDir(tempDir + "emptyDirectory");
QVERIFY(testDir.isEmpty());
QVERIFY(!testDir.isEmpty(QDir::AllEntries));
QVERIFY(!testDir.isEmpty(QDir::AllEntries | QDir::NoDot));
QVERIFY(!testDir.isEmpty(QDir::AllEntries | QDir::NoDotDot));
QVERIFY(QDir(tempDir).removeRecursively());
}
void tst_QDir::nonEmptyDir()
{
const QDir dir(m_dataPath);
QVERIFY(!dir.isEmpty());
}
QTEST_MAIN(tst_QDir)
#include "tst_qdir.moc"