How to open Subdirectories in a directories by using recursive function?

248 views Asked by At

My program is already works well but I want to add one more condition. The program opens a directory and display .h and .cpp files. But if there is a subdirectory, I can not see the .cpp and .h files inside subdirectory. Here is my code:

QFileInfoList MainWindow::getFileListFromDir(const QString &directory)
{
    QDir qdir(directory);
    QFileInfoList fileList = qdir.entryInfoList(QStringList() << "*.h"  << "*.hpp" << "*.c" << "*.cpp", QDir::Files | QDir::AllDirs
                                                                                                  | QDir::NoDotAndDotDot);
    QStringList files;

    return fileList;
}

void MainWindow::on_Browse_clicked()
{
    QString path = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "/home", QFileDialog::ShowDirsOnly |
                                                                                      QFileDialog::DontResolveSymlinks);
    if(path.isEmpty())
        return;

    ui->FullPath->setText(path);
}

 void MainWindow::on_Ok_clicked()
{
    QString path = ui->FullPath->text();
    if(path.isEmpty())
        return;

    ui->tableWidget->setRowCount(0);

    QFileInfoList fileList = getFileListFromDir(path);
    int count = 0;

    foreach(const QFileInfo& file, fileList)
    { 
        count = m_ig->funcCountLines(file.filePath());
        addItemToList(file.filePath(), file.size(), count);
    }
}
1

There are 1 answers

0
HiFile.app - best file manager On BEST ANSWER

Change getFileListFromDir() to call itself recursively for subdirs.

QFileInfoList MainWindow::getFileListFromDir(const QString &directory)
{
    QDir qdir(directory);
    QFileInfoList fileList = qdir.entryInfoList(QStringList() << "*.h"  << "*.hpp" << "*.c" << "*.cpp", QDir::Files);
    
    for (const QFileInfo &subdir : qdir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot))
    {  
        fileList << getFileListFromDir(subdir.absoluteFilePath()); // this is the recursion
    }

    return fileList;
}