ls命令具有一個-r選項,可以遞歸的列出子目錄中的內容。請編寫一個具有同樣功能的程序。


 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 }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM