c++ scandir 按順序讀取文件目錄


參考博客:

linux 系統獲得當前文件夾下存在的所有文件 scandir函數和struct dirent **namelist結構體

scandir目錄篩選出所有.c的文件,高手幫忙,謝謝! [問題點數:40分]

c++按順序讀取目錄內文件

C語言alphasort()函數:依字母順序排序目錄結構

 

這四篇講的都差不多,也比較短,看一遍就ok

過濾器的實現脫離了主函數的,顯得精簡,函數會先過濾在排序:

下面是我結合我的工程做的一個簡單模擬,如果不用過濾器的話,把第三個參數設0,對於返回列表要手動判斷是目錄還是文件:

#include <dirent.h>
#include <string>
#include <iostream>
#include <unistd.h>

using namespace std;

int fileNameFilter(const struct dirent *cur)
{
    std::string str(cur->d_name);
    if (str.find(".jpg") != std::string::npos)
    {
        return 1;
    }
    return 0;
}

int main()
{
    while(1)
    {
        struct dirent **namelist;
        int n = scandir(".", &namelist, fileNameFilter, alphasort);

        if(n < 0)
            cerr << "memery error " << endl;
        else 
            cout << "total number is: " << n << endl;
            
        for( int i = 0; i < n; i++)
        {
            // /* skip . && .. */
            // if(namelist[i]->d_name[0] == '.')
            //     continue;

            cout<<namelist[i]->d_name<<endl;
            free(namelist[i]);
        }
        free(namelist);
        sleep(5);
    }

    return 0;
}

 

可以看到文件確實按照升序排列了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM