遍歷某一目錄,獲取該目錄下所有文件路徑的數組
1 #include <iostream> 2 #include <dirent.h> 3 #include <vector> 4 5 void listDir(char *path, std::vector<std::string> *files) 6 { 7 DIR *directory_pointer; 8 struct dirent *entry; 9 char childpath[512]; //定義一個字符數組,用來存放讀取的路徑 10 char filepath[512]; //定義一個字符數組,用來存放讀取的路徑 11 directory_pointer=opendir(path); 12 memset(childpath,0,sizeof(childpath)); //將字符數組childpath的數組元素全部置零 13 while((entry=readdir(directory_pointer))!=NULL) //讀取pDir打開的目錄,並賦值給ent, 同時判斷是否目錄為空,不為空則執行循環體 14 { 15 if(entry->d_type & DT_DIR) //讀取 打開目錄的文件類型 並與 DT_DIR進行位與運算操作,即如果讀取的d_type類型為DT_DIR (=4 表讀取的為目錄) 16 { 17 if(strcmp(entry->d_name,".")==0 || strcmp(entry->d_name,"..")==0) 18 { 19 //如果讀取的d_name為 . 或者.. 表示讀取的是當前目錄符和上一目錄符, 用contiue跳過,不進行下面的輸出 20 continue; 21 } 22 23 sprintf(childpath,"%s/%s",path,entry->d_name); //如果非. ..則將 路徑 和 文件名d_name 付給childpath, 並在下一行prinf輸出 24 //printf("path:%s\n",childpath); 25 listDir(childpath, files); //遞歸讀取下層的字目錄內容, 因為是遞歸,所以從外往里逐次輸出所有目錄(路徑+目錄名), 26 //然后才在else中由內往外逐次輸出所有文件名 27 } 28 else //如果讀取的d_type類型不是 DT_DIR, 即讀取的不是目錄,而是文件,則直接輸出 d_name, 即輸出文件名 29 { 30 sprintf(filepath,"%s/%s",path,entry->d_name); 31 printf("file path:%s\n",filepath); //輸出文件名 帶上了目錄 32 files->push_back(filepath); 33 } 34 } 35 } 36 37 int main(int argc, const char * argv[]) { 38 // insert code here... 39 std::cout << "ListFile Start!\n"; 40 41 std::string res = "res"; 42 char *path = const_cast<char *>(res.c_str()); 43 std::vector<std::string> files; 44 listDir(path, &files); 45 return 0; 46 }
運行結果: