1 #include <unistd.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <dirent.h> 5 #include <string.h> 6 #include <sys/stat.h> 7 /** 8 * 將數據的目錄和深度一起傳進來 9 */ 10 void printfdir(char *dir, int depth) { 11 12 DIR * dp; //對目錄進行操作 13 struct dirent *entry; //對目錄的數據項進行操作 14 struct stat statbuf; //用來記錄狀態信息 15 if ((dp = opendir(dir)) != NULL) { 16 fprintf(stderr, "不能打開目錄:%s\n", dir); 17 } 18 chdir(dir); //將當前的工作目重定向 19 while ((entry = readdir(dp)) != NULL) { //使用while來對整個目錄進行遍歷 20 lstat(entry->d_name, &statbuf); 21 if (S_ISDIR(statbuf.st_mode)) { //判斷是否是目錄,如果是目錄的話,就遞歸調用進入下一層 22 if (strcmp(".", entry->d_name) == 0 23 || strcmp("..", entry->d_name) == 0) { 24 continue; 25 } 26 printf("%*s%s/\n", depth, " ", entry->d_name); 27 printfdir(entry->d_name, depth + 4); 28 } else { 29 printf("%*s%s/\n", depth, " ", entry->d_name); 30 } 31 32 } 33 chdir(".."); //如果已經瀏覽完,將程序當前的工作目錄定為父目錄 34 closedir(dp);//關閉目錄流 35 } 36 37 int main(void) { 38 printfdir("/home/fjnucse/test",0); 39 return EXIT_SUCCESS; 40 }