Qt统计某一目录下的某一类文件(同一种扩展名)的方法

本文受了https://blog.csdn.net/Zzhouzhou237/article/details/73613561 的启发

下面的函数实现了统计某一类文件,然后将这些文件的名称放入容器Std::vector<QString>中:

void GetFileNameList( QString qstrSuffix, QDir Dir ,std::vector<QString> &FileList)
{
    QFileInfoList subFileList = Dir.entryInfoList(QDir::Files|QDir::CaseSensitive);//过滤条件为只限文件并区分大小写

    for (int i = 0;i < subFileList.size(); i++)
    {
        QString suffix = subFileList[i].suffix();//获取后缀名
        if (suffix.compare(qstrSuffix) == 0)
        {
            //subFileList[i].baseName() + QString(".%1").arg(qstrSuffix) is equivalent to QFileInnfo::fileName()
            FileList.push_back(subFileList[i].baseName() + QString(".%1").arg(qstrSuffix));//a baseName is the base name of the file without the path
        }
    }
}

 以下是使用示例:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDir>
#include <QFile>
#include <vector>

void GetFileNameList( QString, QDir Dir ,std::vector<QString> &FileList);

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

}

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

void GetFileNameList( QString qstrSuffix, QDir Dir ,std::vector<QString> &FileList)
{
    QFileInfoList subFileList = Dir.entryInfoList(QDir::Files|QDir::CaseSensitive);//过滤条件为只限文件并区分大小写

    for (int i = 0;i < subFileList.size(); i++)
    {
        QString suffix = subFileList[i].suffix();//获取后缀名
        if (suffix.compare(qstrSuffix) == 0)
        {
            //subFileList[i].baseName() + QString(".%1").arg(qstrSuffix) is equivalent to QFileInnfo::fileName()
            FileList.push_back(subFileList[i].baseName() + QString(".%1").arg(qstrSuffix));//a baseName is the base name of the file without the path
        }
    }
}

void MainWindow::on_pushButton_clicked()
{
    QString qstrOutput;
    std::vector<QString> fileLst;
    GetFileNameList(QString("mp4"), QDir("C:\\ziji\\youtube"), fileLst);
    std::vector<QString>::iterator itr;
    for(itr = fileLst.begin();itr != fileLst.end(); itr++)
    {
        qstrOutput += *itr + QString("\r\n");
    }
    ui->textEdit->setText(qstrOutput);
}

效果:

发布了148 篇原创文章 · 获赞 46 · 访问量 28万+

猜你喜欢

转载自blog.csdn.net/liji_digital/article/details/103788654