【问题标题】:Check if directory is empty检查目录是否为空
【发布时间】:2013-05-03 04:41:19
【问题描述】:

我正在尝试检查目录是否为空。

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

检查它的正确方法是什么,不包括...

【问题讨论】:

  • @Blender 我的错,只是想检查一下,如果 count 是布尔值?
  • .count() 应该返回一个整数,所以将它与0 比较,而不是"0"
  • 嗯,没关系,无论 Dir 是否为空,与 1 或 0 比较都不会返回任何内容?

标签: qt qt4


【解决方案1】:

好吧,我有办法做到这一点:)

if(QDir("/home/highlander/Desktop/dir").entryInfoList(QDir::NoDotAndDotDot|QDir::AllEntries).count() == 0)
{
    QMessageBox::information(this,"Directory is empty","Empty!!!");
}

【讨论】:

  • QDir::AllEntries 对于隐藏(可能还有系统)文件是不够的。您也应该检查它们。
【解决方案2】:

从 Qt 5.9 开始有了bool QDir::isEmpty(...),因为它更清晰、更快,所以更可取,see docs

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      这是一种方法。

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

      【讨论】:

      • 为什么不直接联系dir.count()&lt;3
      • @HeyYO:这似乎是一个更好的解决方案。为什么不回答并承担责任?
      【解决方案5】:

      或者你可以检查一下;

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

      【讨论】:

      • 那是另一个问题。这是您所提问题的最简单解决方案。
      • 幻数是非常糟糕的做法。在其他平台上可能会有所不同。
      猜你喜欢
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 2011-11-21
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      相关资源
      最近更新 更多