qt 遍历文件夹读取文件
时间: 2024-04-21 20:21:07 浏览: 40
在Qt中,可以使用QDir类来遍历文件夹并读取文件。下面是一个简单的示例代码:
```cpp
#include <QCoreApplication>
#include <QDir>
#include <QDebug>
void traverseFolder(const QString& folderPath)
{
QDir folder(folderPath);
if (!folder.exists()) {
qDebug() << "Folder does not exist.";
return;
}
QStringList files = folder.entryList(QDir::Files);
foreach (QString file, files) {
qDebug() << "File: " << file;
// 在这里可以对文件进行读取操作
}
QStringList subFolders = folder.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (QString subFolder, subFolders) {
QString subFolderPath = folderPath + QDir::separator() + subFolder;
traverseFolder(subFolderPath); // 递归遍历子文件夹
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString folderPath = "your_folder_path";
traverseFolder(folderPath);
return a.exec();
}
```
上述代码中,`traverseFolder`函数用于遍历文件夹并输出文件名。你可以在注释的位置对文件进行读取操作。在`main`函数中,你需要将`folderPath`替换为你要遍历的文件夹路径。