Qt实现遍历文件夹和文件目录

采用递归和QDir实现文件夹下所有文件遍历的方法

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    void InitConnect();
    bool FindFile(const QString &path);

public slots:
    void SlotFindFileAndDir();

private:
    Ui::MainWindow *ui;
    int m_nFilesCount;
    int m_nDirCount;
};

#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 
#include 
#include 
#include 
#include 

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    InitConnect();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::InitConnect()
{
    connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(SlotFindFileAndDir()));
}

bool MainWindow::FindFile(const QString &path)
{
    QDir dir(path);
    if(!dir.exists())
    {
        return false;
    }
    dir.setFilter(QDir::Dirs | QDir::Files);
    dir.setSorting(QDir::DirsFirst);//文件夹排在前面
    QFileInfoList list = dir.entryInfoList();
    int i = 0;

    bool bIsDir;
    do
    {
        QFileInfo fileInfo = list.at(i);
        if(fileInfo.fileName() == "." | fileInfo.fileName() == "..")
        {
            ++i;
            continue;
        }
        bIsDir = fileInfo.isDir();
        if(bIsDir)
        {
            ++m_nDirCount;//目录个数
            FindFile(fileInfo.filePath());
        }
        else
        {
            ++m_nFilesCount;//文件个数
            //fileInfo.fileName() fileInfo.baseName() fileInfo.path() fileInfo.completeSuffix() fileInfo.suffix()
            qDebug() << "groupId=" << fileInfo.groupId() << "lastModified=" << fileInfo.lastModified().toString("yyyy-MM-dd hh:mm:ss") << "absoluteFilePath=" << fileInfo.absoluteFilePath();
        }
        ++i;
    }while(i < list.size());

    return true;
}

void MainWindow::SlotFindFileAndDir()
{
    QString strDir = "E:\\qtproject\\CustomWidget";
    m_nFilesCount = 0;
    m_nDirCount = 0;
    FindFile(strDir);
    qDebug() << "m_nFilesCount=" << m_nFilesCount << "m_nDirCount=" << m_nDirCount;
}

 

 

 

 

 

你可能感兴趣的:(QT)