Qt递归非递归遍历文件

c++
c++, Qt

qt最大的优势在于跨平台,虽然都说qt设计优良,文档丰富,但是qt一直不温不火的。不过跨平台确实可以节省不少人力物力,”一次编写,到处编译“,对于短期搭建框架也有优势.

#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFileInfoList>
#include <QQueue>
#include <QString>
#include <QStringList>
#include <QVector>

QVector<QString> all_files;

void DfsCollectFiles(const QString& filepath)    // not recommended for deep directory
{

    QFileInfo curFileInfo(filepath);
    if (!curFileInfo.isDir())
        return;
    QDir curDir(filepath);

    QFileInfoList curFileInfoList(curDir.entryInfoList());
    if (curFileInfoList.empty())
        return;

    QFileInfoList::const_iterator it;
    for (it = curFileInfoList.begin(); it != curFileInfoList.end(); ++it) {
        if (it->isDir() && it->fileName() != "."  && it->fileName() != "..") {
            DfsCollectFiles(it->absoluteFilePath());    //recursively
        } else if (!it->isDir()) {
            all_files.push_back(it->absoluteFilePath());
        }
    }

}

void BfsCollectFiles(const QString& filepath)     // bfs traverse
{
    QFileInfo cur_fileinfo(filepath);
    QQueue<QFileInfo> fileinfo_queue;    // queue
    QDir cur_dir(filepath);

    fileinfo_queue.enqueue(cur_fileinfo);
    while (!fileinfo_queue.isEmpty()) {
        cur_dir = fileinfo_queue.head().absoluteFilePath();
        fileinfo_queue.dequeue();
        QFileInfoList cur_fileinfolist = cur_dir.entryInfoList();

        QFileInfoList::const_iterator it;
        for (it = cur_fileinfolist.cbegin(); it != cur_fileinfolist.cend(); ++it) {
            if (it->isDir() && it->fileName() != "." && it->fileName() != "..") {    // jump "." and ".."
                fileinfo_queue.enqueue(it->absoluteFilePath());    // enqueue unresolved directories
            } else if (!it->isDir()){
                all_files.push_back(it->absoluteFilePath());
            }
        }
    }

}

测试代码:

int main()
{
    QString  filepath("/home/wnn/tmp");
    QVector<QString>::const_iterator it;

    DfsCollectFiles(filepath);
    qDebug() << all_files.size();
    for (it = all_files.cbegin(); it != all_files.cend(); ++it)
        qDebug() << *it;
    qDebug() << endl;

    all_files.clear();

    BfsCollectFiles(filepath);
    for (it = all_files.cbegin(); it != all_files.cend(); ++it)
            qDebug() << *it;
    qDebug() << all_files.size();

    return 0;
}

关于上面代码命名的约定,类名和函数名用驼峰命名法,类的成员函数和qt一样用“小驼峰命名法”, 非成员函数用“大驼峰命名法”,变量名统一用小写字母加下划线,这样从名称就可以判定一个成员是什么类别。遍历完所有文件就可以自行根据绝对路径处理了。

类似用shell列出文件:
ls -R | egrep "*.pdf" #列出所有pdf文件

不过还是python简单粗暴:

import os

def cur_walk(curDir):
    for parent, dirnames, filenames in os.walk(curDir):
        for filename in filenames:    #files
            print os.path.abspath(os.path.join(parent, filename))
    for dirname in dirnames:    #directory
        print os.path.abspath(os.path.join(parent, dirname))

curDir = '/home/wnn/tmp'
cur_walk(curDir)

来一首二哥的新歌: