- 论坛徽章:
- 0
|
本帖最后由 ran3guns 于 2012-06-02 22:05 编辑
回复 1# evaspring
1. 你要遍历目录(树),自然是遍历代码简单了。树的遍历当然可以写成非递归,但是太麻烦了。
2. 不调用chdir, 改变工作目录,这个可以用一个保存路径来达到。附个代码:- /*
- * =====================================================================================
- * Filename: scandir.c
- * Description: scan the directory and print all the files
- * except hide
- * Version: 1.0
- * Created: 06/02/2012 09:40:15 PM
- * Revision: none
- * Compiler: gcc
- * Author: ran3guns
- * =====================================================================================
- */
- #include <unistd.h>
- #include <dirent.h>
- #include <sys/stat.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <limits.h>
- static void scan_dir(const char *path, int depth);
- static char FULLPATH[PATH_MAX + 1];
- int main(int argc, const char *argv[])
- {
- const char *pathname;
- int depth = 0;
- if (2 != argc) {
- fprintf(stderr, "Usage: ./scan_dir <path-name>\n");
- exit(EXIT_FAILURE);
- }
- pathname = argv[1];
- strncpy(FULLPATH, pathname, strlen(pathname) + 1);
- scan_dir(FULLPATH, depth);
- exit(EXIT_SUCCESS);
- }
- static void scan_dir(const char *path, int depth)
- {
- struct stat statbuf;
- struct dirent *dirp;
- DIR *dp;
- char *ep;
-
- if ((dp = opendir(FULLPATH)) == NULL) {
- fprintf(stderr, "cannot open %s\n", FULLPATH);
- return;
- }
- ep = FULLPATH + strlen(FULLPATH);
- *ep++ = '/';
- *ep = 0;
- while ((dirp = readdir(dp)) != NULL) {
- lstat(dirp->d_name, &statbuf);
- if (S_ISDIR(statbuf.st_mode)) {
- if (strcmp(".", dirp->d_name) == 0 ||
- strcmp("..", dirp->d_name) == 0)
- continue;
- printf("%*s%s\n", depth," ", dirp->d_name);
- strcpy(ep, dirp->d_name); /* use a full path instead of chdir */
- scan_dir(FULLPATH, depth + 4);
- }
- else {
- if (dirp->d_name[0] != '.') /* except the hide files */
- printf("%*s%s\n", depth, " ", dirp->d_name);
- }
- }
- ep[-1] = '\0';
- closedir(dp);
- }
复制代码 |
|