6

I'm trying to check if a directory is empty.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QDir Dir("/home/highlander/Desktop/dir");
    if(Dir.count() == 0)
    {
        QMessageBox::information(this,"Directory is empty","Empty!!!");
    }
}

Whats the right way to check it, excluding . and ..?

awesoon
  • 32,469
  • 11
  • 74
  • 99
highlander141
  • 1,683
  • 3
  • 23
  • 48

5 Answers5

24

Well, I got the way to do it :)

if(QDir("/home/highlander/Desktop/dir").entryInfoList(QDir::NoDotAndDotDot|QDir::AllEntries).count() == 0)
{
    QMessageBox::information(this,"Directory is empty","Empty!!!");
}
highlander141
  • 1,683
  • 3
  • 23
  • 48
  • 2
    QDir::AllEntries is not enough for hidden (and possibly system) files. You should check for them as well. – Kirinyale Jul 05 '13 at 12:00
5

Since Qt 5.9 there is bool QDir::isEmpty(...), which is preferable as it is clearer and faster, see docs:

Equivalent to count() == 0 with filters QDir::AllEntries | QDir::NoDotAndDotDot, but faster as it just checks whether the directory contains at least one entry.

Martin R.
  • 1,554
  • 17
  • 16
2

As Kirinyale pointed out, hidden and system files (like socket files) are not counted in highlander141's answer. To count these as well, consider the following method:

bool dirIsEmpty(const QDir& _dir)
{
    QFileInfoList infoList = _dir.entryInfoList(QDir::AllEntries | QDir::System | QDir::NoDotAndDotDot | QDir::Hidden );
    return infoList.isEmpty();
}
spawn
  • 192
  • 3
  • 9
1

This is one way of doing it.

#include <QCoreApplication>
#include <QDir>
#include <QDebug>
#include <QDesktopServices>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc,argv);

    QDir dir(QDesktopServices::storageLocation(QDesktopServices::DesktopLocation));

    QStringList list = dir.entryList();
    int count;
    for(int x=0;x<list.count(); x++)
    {
        if(list.at(x) != "." && list.at(x) != "..")
        {
            count++;
        }
    }

    qDebug() << "This directory has " << count << " files in it.";
    return 0;
}
0

Or you could just check with;

if(dir.count()<3){
    ... //empty dir
}
HeyYO
  • 1,989
  • 17
  • 24