QDir
Qt中对目录遍历的支持是比较好的,比如QDir、QFileInfo、QFile等。 在Qt助手中可以查到有关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;
}