Check if directory is empty

半城伤御伤魂 提交于 2019-12-22 06:34:31

问题


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:


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.




回答4:


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



回答5:


Or you could just check with;

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


来源:https://stackoverflow.com/questions/16351699/check-if-directory-is-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!