1. 程式人生 > >linux C 遍歷目錄及其子目錄 opendir -> readdir -> closedir

linux C 遍歷目錄及其子目錄 opendir -> readdir -> closedir

複製程式碼
 1 #include <stdio.h>  
 2 #include <string.h> 
 3 #include <stdlib.h>  
 4 #include <dirent.h>  
 5 #include <sys/stat.h>  
 6 #include <unistd.h>  
 7 #include <sys/types.h> 
 8 #include <iostream>
 9 
10 
11 using namespace std;
12 void listDir(char *path)  //main函式的argv[1] char * 作為 所需要遍歷的路徑 傳引數給listDir   
13 { 14 DIR *pDir ; //定義一個DIR類的指標 15 struct dirent *ent ; //定義一個結構體 dirent的指標,dirent結構體見上 16 int i=0 ; 17 char childpath[512]; //定義一個字元陣列,用來存放讀取的路徑 18 19 pDir=opendir(path); // opendir方法開啟path目錄,並將地址付給pDir指標 20 memset(childpath,0
,sizeof(childpath)); //將字元陣列childpath的陣列元素全部置零 21 22 23 while((ent=readdir(pDir))!=NULL) //讀取pDir開啟的目錄,並賦值給ent, 同時判斷是否目錄為空,不為空則執行迴圈體 24 { 25 26 if(ent->d_type & DT_DIR) //讀取 開啟目錄的檔案型別 並與 DT_DIR進行位與運算操作,即如果讀取的d_type型別為DT_DIR (=4 表示讀取的為目錄) 27 {
28 29 if(strcmp(ent->d_name,".")==0 || strcmp(ent->d_name,"..")==0)                                        //如果讀取的d_name為 . 或者.. 表示讀取的是當前目錄符和上一目錄符, 用contiue跳過,不進行下面的輸出 30 continue; 31 32 sprintf(childpath,"%s/%s",path,ent->d_name); //如果非. ..則將 路徑 和 檔名d_name 付給childpath, 並在下一行prinf輸出 33 printf("path:%s\n",childpath); 34 35 listDir(childpath); //遞迴讀取下層的字目錄內容, 因為是遞迴,所以從外往裡逐次輸出所有目錄(路徑+目錄名),                                             //然後才在else中由內往外逐次輸出所有檔名 36 37 } 38               else //如果讀取的d_type型別不是 DT_DIR, 即讀取的不是目錄,而是檔案,則直接輸出 d_name, 即輸出檔名 39               { 40                   cout<<ent->d_name<<endl; //cout<<childpath<<"/"<<ent->d_name<<endl; 輸出檔名 帶上了目錄 41               } 42 } 43 44 } 45 46 int main(int argc,char *argv[]) 47 { 48 listDir(argv[1]); //第一個引數為 想要遍歷的 linux 目錄 例如,當前目錄為 ./ ,上一層目錄為../ 49 return 0; 50 }
複製程式碼