前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >QDir示例

QDir示例

作者头像
ccf19881030
发布2021-04-27 16:33:46
9130
发布2021-04-27 16:33:46
举报
文章被收录于专栏:ccf19881030的博客ccf19881030的博客

QDir

Qt中对目录遍历的支持是比较好的,比如QDir、QFileInfo、QFile等。 在Qt助手中可以查到有关QDir的用法,如下图所示:

QDir
QDir

下面是我本人测试的一些关于QDir类的测试代码:

代码语言:javascript
复制
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <QString>

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

    qDebug() << "the directory of application's executable" << QCoreApplication::applicationDirPath() << endl;

    QDir dir("D:/env/aaa");
    if (!dir.exists())
    {
        qWarning("Cannot find the D:/env directory");
    } else {
        qDebug() << "D/env exists" << endl;
    }

    QDir mDir;

    foreach(QFileInfo mFileInfoItem, mDir.drives())
    {
        qDebug() << mFileInfoItem.absoluteFilePath() << endl;
    }

    QDir myDir;
    QString mPath = "E:/Test/ZZZ";

    if (!myDir.exists(mPath))
    {
        myDir.mkpath(mPath);
        qDebug () << mPath << " Created!" << endl;
    }
    else {
        qDebug() << mPath << " Already exists" << endl;
    }

    QDir dDir("E:/SoftDevelop/CPlus/QtProjects/Qt5Samples/MyQtDemos");

    foreach(QFileInfo mItem, dDir.entryInfoList())
    {
        if (mItem.isDir())
        {
            qDebug() << "Dir: " << mItem.absoluteFilePath() << endl;
        }
        if (mItem.isFile())
        {
            qDebug() << "File: " << mItem.absoluteFilePath() << endl;
        }
    }

    return a.exec();
}

下面是Qt官方帮助文档提供的关于QtDir的一个完整示例代码:

代码语言:javascript
复制
// A program that lists all the files in the current directory (excluding symbolic links), sorted by size, smallest first:

  #include <QDir>
  #include <iostream>

  int main(int argc, char *argv[])
  {
      QCoreApplication app(argc, argv);
      QDir dir;
      dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
      dir.setSorting(QDir::Size | QDir::Reversed);

      QFileInfoList list = dir.entryInfoList();
      std::cout << "     Bytes Filename" << std::endl;
      for (int i = 0; i < list.size(); ++i) {
          QFileInfo fileInfo = list.at(i);
          std::cout << qPrintable(QString("%1 %2").arg(fileInfo.size(), 10)
                                                  .arg(fileInfo.fileName()));
          std::cout << std::endl;
      }
      return 0;
  }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-04-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • QDir
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档