目錄遍歷函數(14)
dirent結構體和d_type
代碼:
1 /* 2 // 打開一個目錄 3 #include <sys/types.h> 4 #include <dirent.h> 5 DIR *opendir(const char *name); 6 參數: 7 - name: 需要打開的目錄的名稱 8 返回值: 9 DIR * 類型,理解爲目錄流 10 錯誤返回NULL 11 12 13 // 讀取目錄中的數據 14 #include <dirent.h> 15 struct dirent *readdir(DIR *dirp); 16 - 參數:dirp是opendir返回的結果 17 - 返回值: 18 struct dirent,代表讀取到的文件的信息 19 讀取到了末尾或者失敗了,返回NULL 20 21 // 關閉目錄 22 #include <sys/types.h> 23 #include <dirent.h> 24 int closedir(DIR *dirp); 25 26 */ 27 #include <sys/types.h> 28 #include <dirent.h> 29 #include <stdio.h> 30 #include <string.h> 31 #include <stdlib.h> 32 33 int getFileNum(const char * path); 34 35 // 讀取某個目錄下所有的普通文件的個數 36 int main(int argc, char * argv[]) { 37 38 if(argc < 2) { 39 printf("%s path\n", argv[0]); 40 return -1; 41 } 42 43 int num = getFileNum(argv[1]); 44 45 printf("普通文件的個數爲:%d\n", num); 46 47 return 0; 48 } 49 50 // 用於獲取目錄下所有普通文件的個數 51 int getFileNum(const char * path) { 52 53 // 1.打開目錄 54 DIR * dir = opendir(path); 55 56 if(dir == NULL) { 57 perror("opendir"); 58 exit(0); 59 } 60 61 struct dirent *ptr; 62 63 // 記錄普通文件的個數 64 int total = 0; 65 66 while((ptr = readdir(dir)) != NULL) { 67 68 // 獲取名稱 69 char * dname = ptr->d_name; 70 71 // 忽略掉. 和.. 72 if(strcmp(dname, ".") == 0 || strcmp(dname, "..") == 0) { 73 continue; 74 } 75 76 // 判斷是否是普通文件還是目錄 77 if(ptr->d_type == DT_DIR) { 78 // 目錄,需要繼續讀取這個目錄 79 char newpath[256]; 80 sprintf(newpath, "%s/%s", path, dname); 81 total += getFileNum(newpath); 82 } 83 84 if(ptr->d_type == DT_REG) { 85 // 普通文件 86 total++; 87 } 88 89 90 } 91 92 // 關閉目錄 93 closedir(dir); 94 95 return total; 96 }