shy丶gril 2016-05-20 1191浏览量
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 }
作者:kissazi2
出处:http://www.cnblogs.com/kissazi2/
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
转载:http://www.cnblogs.com/kissazi2/archive/2013/01/20/2868273.html
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
时时分享云计算技术内容,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。