文件系统树遍历

时间:2012-02-23 17:23:35

标签: c linux file filesystems traversal

我正在编写一个C程序来遍历文件系统树。我知道ftw()但我想自己做。问题是我希望我的C程序访问每个节点(目录/文件),而不必为每个节点执行pathlookup(当然是隐式地完成但也想避免这样做)。

谢谢

说一个目录A有两个孩子B和C.我想到达每个B和C的方法是读取C的内容和访问B和C的路径/ A / B和/ A / C.但是想要在路径中直接从A

中的引用访问B和C.

2 个答案:

答案 0 :(得分:2)

您可以使用chdiropenat代替fdopendir来避免opendir的重复路径查找和丑陋(全局状态和非线程安全)穿过树。

答案 1 :(得分:1)

下面:

#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>

void printdir(char *dir, int depth)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;
    int spaces = depth*4;

    if((dp = opendir(dir)) == NULL) {
        fprintf(stderr,"cannot open directory: %s\n", dir);
        return;
    }
    chdir(dir);
    while((entry = readdir(dp)) != NULL) {
        lstat(entry->d_name,&statbuf);
        if(S_ISDIR(statbuf.st_mode)) {
            /* Found a directory, but ignore . and .. */
            if(strcmp(".",entry->d_name) == 0 || 
                strcmp("..",entry->d_name) == 0)
                continue;
            printf("%*s%s/\n",spaces,"",entry->d_name);
            /* Recurse at a new indent level */
            printdir(entry->d_name,depth+1);
        }
        else printf("%*s%s\n",spaces,"",entry->d_name);
    }
    chdir("..");
    closedir(dp);
}

/*  Now we move onto the main function.  */

int main(int argc, char* argv[])
{
    char *topdir, pwd[2]=".";
    if (argc != 2)
        topdir=pwd;
    else
        topdir=argv[1];

    printf("Directory scan of %s\n",topdir);
    printdir(topdir,0);
    printf("done.\n");

    return 0;
}

Link to the original paper

相关问题