Check if directory is empty

2019-04-29 12:05发布

问题:

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 ..?

回答1:

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!!!");
}


回答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();
}


回答3:

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;
}


回答4:

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.



回答5:

Or you could just check with;

if(dir.count()<3){
    ... //empty dir
}


标签: qt qt4