在学习APUE文件和目录一章中,关于目录的递归遍历问题我一直很感兴趣,并想实现类似于tree命令的功能,经过仔细分析APUE fig4-7的原理并加以修改,终于实现了该功能。先给出运行效果如下:
实现代码如下:
- #include "apue.h"
- static int depth;
- static char fullpath[255];
- typedef void Myfunc(const char *, int);
- #define end(s) ((char *)(s) + strlen(s))
- static void pr_fname(const char *dname, int depth);
- static void dir_walk(Myfunc func, const char *dname);
- int main(int argc, char *argv[])
- {
- if (argc != 2) return 0;
- strcpy(fullpath, argv[1]);
- dir_walk(pr_fname, fullpath);
- return 0;
- }
- static void dir_walk(Myfunc func, const char *dname)
- {
- struct stat statbuf;
- if (stat(fullpath, &statbuf) < 0)
- err_ret("stat error %s", fullpath);
- if (S_ISDIR(statbuf.st_mode) == 0) {
- func(dname, depth);
- return;
- }
- func(dname, depth++);
- char *ptr = end(fullpath);
- strcat(ptr++, "/");
- struct dirent *dirp;
- DIR *dp = opendir(fullpath);
- while ((dirp = readdir(dp)) != NULL) {
- if (strcmp(dirp->d_name, ".") == 0 ||
- strcmp(dirp->d_name, "..") == 0)
- continue;
- strcpy(ptr, dirp->d_name);
- dir_walk(func, dirp->d_name);
- }
- ptr[-1] = 0;
- depth--;
- closedir(dp);
- }
- static void pr_fname(const char *dname, int depth)
- {
- int i = 0, dep = 0;
- for ( ; i < depth * 4 - 1; i++) {
- if (!(i & 3)) {
- fprintf(stdout, "|");
- if (i) dep++;
- }
- if (dep + 1 == depth)
- fprintf(stdout, "-");
- else fprintf(stdout, " ");
- }
- fprintf(stdout, " %s\n", dname);
- }
原理就不赘述了,相信大家都不难看明白。
阅读(2957) | 评论(0) | 转发(0) |