簡體   English   中英

計算文件夾中的文件(包括子文件夾)

[英]Count File in a folder (include subfolder)

嗨,我使用 Qt,我想知道文件夾中有多少文件(包括子文件夾)我在互聯網上找到了一些代碼,但它們都只計算文件夾中的文件,而不是其子文件夾
喜歡這個代碼

#include <stdio.h>
#include <dirent.h>

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("Usage: ./count \"<path>\"\n");
        return 1;
    }

    struct dirent *de;
    DIR *dir = opendir(argv[1]);
    if(!dir)
    {
        printf("opendir() failed! Does it exist?\n");
        return 1;
    }

    unsigned long count=0;
        while(de = readdir(dir))
     {
          ++count;
     }

    closedir(dir);
    printf("%lu\n", count);

    return 0;
}

在這里找到這個代碼,它只計算文件夾中的文件,而不是它的子文件夾
任何人都可以幫助我
編輯 1
我從這個頁面測試了這段代碼,它可以工作,但它可以編輯以減少 CPU 使用率?

以下代碼為 Qt 運行。

QStringList nameFilters;
nameFilters << "*.jpg";
QDirIterator it(QDir::currentPath(), nameFilters, QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()) {
    qDebug() << it.next();
}

使用nameFilters << "*"; 如果您想知道父目錄及其子目錄中的所有文件。

sumit_smk 代碼沒問題,但需要對您的情況稍作修改
這是您可以使用的代碼

int file = 0;
QDirIterator it("/Your_folder/", QDir::Files, QDirIterator::Subdirectories);
    while (it.hasNext())
    {
        if(it.next() > 0 )
        {
            file++;
        }
    }
    qDebug() << file;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM