标签:.com amp pwd 文件目录 pre sed read 技术 lib
通过递归调用读取目录和文件信息去遍历整个目录:
示例代码:
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 }
运行结果:
标签:.com amp pwd 文件目录 pre sed read 技术 lib
原文地址:http://www.cnblogs.com/general0878/p/7214244.html