- 论坛徽章:
- 0
|
怎样遍历一个指定的目录
代码:
- //create by WangHonglei
- #include <sys/stat.h>;
- #include <dirent.h>;
- #include <unistd.h>;
- #include <stdlib.h>;
- #include <stdio.h>;
- #include <string.h>;
- static int indent = 0;
- char cdir[256];
- void GetFileName(char *file)
- {
- printf("%s/%s\n", getcwd(cdir, 256),file);
- }
- void Scandir(char *wd, void (*func)(char *), int depth)
- {
- struct dirent **items;
- int nitems, i;
- if (chdir(wd) < 0)
- {
- printf("DIR : %s\n", wd);
- perror("chdir ");
- exit(1);
- }
- nitems = scandir(".", &items, NULL, alphasort);
- for (i = 0; i < nitems; i++)
- {
- struct stat fstat;
- if ( (!strcmp(items[i]->;d_name, ".")) || (!strcmp(items[i]->;d_name, "..")) )
- {
- continue;
- }
- func(items[i]->;d_name);
- lstat(items[i]->;d_name, &fstat);
- if ((fstat.st_mode & S_IFDIR) == S_IFDIR)
- {
- if (indent < (depth-1) || (depth == 0))
- {
- indent ++;
- Scandir(items[i]->;d_name, func, depth);
- }
- }
- }
- indent --;
- chdir("..");
- }
-
- int
- main()
- {
- Scandir("/tmp", GetFileName, 1);
- return 0;
- }
复制代码 |
|