Qt 遍历目录

遍历目录主要用QDir

参考:

https://www.cnblogs.com/findumars/p/6006129.html

http://blog.sina.com.cn/s/blog_a6fb6cc90101f1ur.html

示例:

QFileInfoList CDialogLoadFile::GetFileList(QString path)
{
    QDir dir(path);
    QStringList nameFilters;
    nameFilters << ".txt";
    QFileInfoList file_list = dir.entryInfoList(nameFilters,QDir::Files | QDir::Hidden | QDir::NoSymLinks);
    QFileInfoList folder_list = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);

    for(int i = 0; i != folder_list.size(); i++)
    {
         QString name = folder_list.at(i).absoluteFilePath();
         QFileInfoList child_file_list = GetFileList(name);
         file_list.append(child_file_list);
    }
    return file_list;
}

主要的API是entryInfoList

搬一下F1(Qt的F1真的不错,虽然有时也不那么完善)

QFileInfoList QDir::entryInfoList ( Filters filters = NoFilter, SortFlags sort = NoSort ) const
This is an overloaded function.

Returns a list of QFileInfo objects for all the files and directories in the directory, ordered according to the name and attribute filters previously set with setNameFilters() and setFilter(), and sorted according to the flags set with setSorting().

The attribute filter and sorting specifications can be overridden using the filters and sort arguments.

Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.

 

### 在 Qt遍历 QRC 资源文件内部目录的示例代码 在 Qt 中,可以使用 `QResource` 类来访问和遍历嵌入到应用程序中的资源文件。以下是一个完整的示例代码,展示如何遍历 `.qrc` 文件中的目录和文件[^1]。 ```cpp #include <QCoreApplication> #include <QDir> #include <QFile> #include <QResource> #include <QDebug> void traverseResources(const QString &prefix = "/") { // 遍历资源系统中的所有条目 for (const QFileInfo &entry : QResource::system()->children(prefix)) { QString entryPath = prefix + entry.fileName(); if (entry.isDir()) { qDebug() << "Directory:" << entryPath; // 递归遍历目录 traverseResources(entryPath + "/"); } else if (entry.isFile()) { qDebug() << "File:" << entryPath; // 如果需要读取文件内容,可以打开并读取 QFile file(entryPath); if (file.open(QIODevice::ReadOnly)) { QByteArray content = file.readAll(); qDebug() << "Content of" << entryPath << ":" << content; file.close(); } } } } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); // 确保资源系统已初始化 Q_INIT_RESOURCE(resources); // 替换为实际的 .qrc 文件名[^2] qDebug() << "Start traversing resources..."; traverseResources(); // 开始遍历资源 return app.exec(); } ``` #### 说明 1. 使用 `QResource::system()->children()` 方法可以获取指定路径下的所有子目录和文件。 2. 对于每个条目,通过 `QFileInfo` 判断其是否为目录或文件,并分别处理。 3. 如果需要读取文件内容,可以使用 `QFile` 打开并读取资源文件的内容。 4. 调用 `Q_INIT_RESOURCE()` 来确保资源系统被正确初始化[^3]。 ### 注意事项 - 确保 `.qrc` 文件已被正确编译并链接到项目中。 - 如果资源文件较大,可能会对内存使用产生影响,需谨慎设计资源结构[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值