參考博客:
linux 系統獲得當前文件夾下存在的所有文件 scandir函數和struct dirent **namelist結構體
scandir目錄篩選出所有.c的文件,高手幫忙,謝謝! [問題點數:40分]
這四篇講的都差不多,也比較短,看一遍就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; }
可以看到文件確實按照升序排列了