免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1606 | 回复: 4
打印 上一主题 下一主题

怎样遍历一个指定的目录 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2004-04-12 17:33 |只看该作者 |倒序浏览
请问怎样遍历一个指定目录下的所有一级目录?

论坛徽章:
1
2015年辞旧岁徽章
日期:2015-03-03 16:54:15
2 [报告]
发表于 2004-04-12 17:48 |只看该作者

怎样遍历一个指定的目录

man opendir
man readdir

论坛徽章:
0
3 [报告]
发表于 2004-04-13 14:37 |只看该作者

怎样遍历一个指定的目录

scandir()
~~~~~~~~~

论坛徽章:
0
4 [报告]
发表于 2004-04-13 16:14 |只看该作者

怎样遍历一个指定的目录

用法写一写好吗,共享一下知识,谢谢.

论坛徽章:
0
5 [报告]
发表于 2004-04-13 17:12 |只看该作者

怎样遍历一个指定的目录

代码:


  1. //create by WangHonglei
  2. #include <sys/stat.h>;
  3. #include <dirent.h>;
  4. #include <unistd.h>;
  5. #include <stdlib.h>;
  6. #include <stdio.h>;
  7. #include <string.h>;

  8. static int  indent = 0;

  9. char cdir[256];
  10. void GetFileName(char *file)
  11. {
  12.     printf("%s/%s\n", getcwd(cdir, 256),file);
  13. }

  14. void Scandir(char *wd, void (*func)(char *), int depth)
  15. {
  16.     struct dirent **items;
  17.     int nitems, i;
  18.     if (chdir(wd) < 0)
  19.     {
  20.         printf("DIR : %s\n", wd);
  21.         perror("chdir ");
  22.         exit(1);
  23.     }


  24.     nitems = scandir(".", &items, NULL, alphasort);

  25.     for (i = 0; i < nitems; i++)
  26.     {
  27.         struct stat fstat;

  28.         if ( (!strcmp(items[i]->;d_name, ".")) || (!strcmp(items[i]->;d_name, "..")) )
  29.         {
  30.             continue;
  31.         }

  32.         func(items[i]->;d_name);

  33.         lstat(items[i]->;d_name, &fstat);
  34.         if ((fstat.st_mode & S_IFDIR) == S_IFDIR)
  35.         {
  36.             if (indent < (depth-1) || (depth == 0))
  37.             {
  38.                    indent ++;
  39.                  Scandir(items[i]->;d_name, func, depth);
  40.             }

  41.         }
  42.     }
  43.     indent --;
  44.     chdir("..");
  45. }



  46. int
  47. main()
  48. {
  49.     Scandir("/tmp",  GetFileName,  1);
  50.     return 0;
  51. }

复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP