Chinaunix首页 | 论坛 | 博客
  • 博客访问: 188929
  • 博文数量: 27
  • 博客积分: 725
  • 博客等级: 上士
  • 技术积分: 347
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-04 09:01
文章分类

全部博文(27)

文章存档

2012年(15)

2011年(12)

分类: LINUX

2011-12-07 08:51:27

在学习APUE文件和目录一章中,关于目录的递归遍历问题我一直很感兴趣,并想实现类似于tree命令的功能,经过仔细分析APUE fig4-7的原理并加以修改,终于实现了该功能。先给出运行效果如下:
 
实现代码如下:
  1. #include "apue.h"

  2. static int depth;
  3. static char fullpath[255];
  4. typedef void Myfunc(const char *, int);

  5. #define end(s) ((char *)(s) + strlen(s))

  6. static void pr_fname(const char *dname, int depth);
  7. static void dir_walk(Myfunc func, const char *dname);

  8. int main(int argc, char *argv[])
  9. {
  10.     if (argc != 2) return 0;
  11.     strcpy(fullpath, argv[1]);
  12.     dir_walk(pr_fname, fullpath);
  13.     return 0;
  14. }

  15. static void dir_walk(Myfunc func, const char *dname)
  16. {
  17.     struct stat statbuf;
  18.     if (stat(fullpath, &statbuf) < 0)
  19.         err_ret("stat error %s", fullpath);
  20.     if (S_ISDIR(statbuf.st_mode) == 0) {
  21.         func(dname, depth);
  22.         return;
  23.     }

  24.     func(dname, depth++);

  25.     char *ptr = end(fullpath);
  26.     strcat(ptr++, "/");

  27.     struct dirent *dirp;
  28.     DIR *dp = opendir(fullpath);
  29.     while ((dirp = readdir(dp)) != NULL) {
  30.         if (strcmp(dirp->d_name, ".") == 0 ||
  31.                 strcmp(dirp->d_name, "..") == 0)
  32.             continue;
  33.         strcpy(ptr, dirp->d_name);
  34.         dir_walk(func, dirp->d_name);
  35.     }
  36.     ptr[-1] = 0;
  37.     depth--;
  38.     closedir(dp);
  39. }

  40. static void pr_fname(const char *dname, int depth)
  41. {
  42.     int i = 0, dep = 0;
  43.     for ( ; i < depth * 4 - 1; i++) {
  44.         if (!(i & 3)) {
  45.                 fprintf(stdout, "|");
  46.                 if (i) dep++;
  47.         }
  48.         if (dep + 1 == depth)
  49.             fprintf(stdout, "-");
  50.         else fprintf(stdout, " ");
  51.     }
  52.     fprintf(stdout, " %s\n", dname);
  53. }
原理就不赘述了,相信大家都不难看明白。
阅读(2916) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~