1. 程式人生 > >linux 下的文件目錄操作之遍歷目錄

linux 下的文件目錄操作之遍歷目錄

ges div strcmp pen fprintf pwd edi while font

  通過遞歸調用讀取目錄和文件信息去遍歷整個目錄:

  示例代碼:

 1 #include <unistd.h>
 2 #include <stdio.h>
 3 #include <dirent.h>
 4 #include <string.h>
 5 #include <sys/stat.h>
 6 #include <stdlib.h>
 7 
 8 
 9 void printdir(char * dir, int depth)
10 {
11     DIR * dp = opendir(dir);
12     if
(NULL == dp) 13 { 14 fprintf(stderr, "cannot open directory: %s\n", dir); 15 return; 16 } 17 chdir(dir); 18 struct dirent * entry; 19 struct stat statbuf; 20 while ((entry = readdir(dp)) != NULL) 21 { 22 stat(entry->d_name, &statbuf); 23 if
(S_ISDIR(statbuf.st_mode)) 24 { 25 if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0) 26 continue; 27 printf("%*s%s/\n", depth, "", entry->d_name); 28 printdir(entry->d_name, depth + 4); 29 } 30 else
31 printf("%*s%s\n", depth, "", entry->d_name); 32 //printf("%*s",4,"*"); 該函數表示輸出"___*",前面輸出3個空格。 33 //如果是printf("%*s",4,"**");則表示輸出"__**",前面輸出2個空格。 34 } 35 chdir(".."); 36 closedir(dp); 37 } 38 39 int main(int argc, char * argv[]) 40 { 41 char * topdir, pwd[2] = "."; 42 if (argc < 2) 43 topdir = pwd; 44 else 45 topdir = argv[1]; 46 printf("Directory scan of %s\n", topdir); 47 printdir(topdir, 0); 48 printf("done.\n"); 49 exit(0); 50 }

  運行結果:

  技術分享

linux 下的文件目錄操作之遍歷目錄