Chinaunix

标题: 怎样遍历一个指定的目录 [打印本页]

作者: xiyang    时间: 2004-04-12 17:33
标题: 怎样遍历一个指定的目录
请问怎样遍历一个指定目录下的所有一级目录?
作者: flw    时间: 2004-04-12 17:48
标题: 怎样遍历一个指定的目录
man opendir
man readdir
作者: xiyang    时间: 2004-04-13 14:37
标题: 怎样遍历一个指定的目录
scandir()
~~~~~~~~~
作者: dysnake    时间: 2004-04-13 16:14
标题: 怎样遍历一个指定的目录
用法写一写好吗,共享一下知识,谢谢.
作者: smartham_whl    时间: 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. }

复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2