Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Qt 检查目录是否为空_Qt_Qt4 - Fatal编程技术网

Qt 检查目录是否为空

Qt 检查目录是否为空,qt,qt4,Qt,Qt4,我正在检查目录是否为空 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,"

我正在检查目录是否为空

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

除了
之外,正确的检查方法是什么?
这是一种方法

#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;
}
#包括
#包括
#包括
#包括
int main(int argc,char*argv[])
{
QCore应用程序应用程序(argc、argv);
QDir目录(QDesktopServices::storageLocation(QDesktopServices::DesktopLocation));
QStringList list=dir.entryList();
整数计数;

对于(intx=0;x嗯,我找到了方法:)


或者你也可以去看看

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

if(dir.count(),正如Kirinyale指出的,隐藏和系统文件(如套接字文件)
在highlander141的回答中不包括。
要计算这些,也可以考虑以下方法:

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

由于Qt5.9有
boolqdir::isEmpty(…)
,这是最好的,因为它更清晰、更快:

相当于count()==0,带有过滤器QDir::AllEntries | QDir::NodeAndDotDot,但速度更快,因为它只检查目录是否包含至少一个条目


@Blender my bad,只是想检查一下,count是否是bool?
。count()
应该返回一个整数,所以将其与
0
,而不是
“0”
。好吧,没关系,与1或0比较并不会返回任何Dir是否为空的信息。为什么不直接用
Dir.count()检查一下呢@HeyYO:这似乎是一个更好的解决方案。为什么不回答并获得荣誉呢?这是另一个问题。这是解决您所问问题的最简单的解决方案。幻数是非常糟糕的做法。在其他平台上可能会有所不同。QDir::AllEntries对于隐藏(可能是系统)文件来说是不够的。您还应该检查它们。
bool dirIsEmpty(const QDir& _dir)
{
    QFileInfoList infoList = _dir.entryInfoList(QDir::AllEntries | QDir::System | QDir::NoDotAndDotDot | QDir::Hidden );
    return infoList.isEmpty();
}