【问题标题】:File system tree traversal文件系统树遍历
【发布时间】:2012-02-23 17:23:34
【问题描述】:

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

谢谢

假设一个目录 A 有两个孩子 B 和 C。我到达每个 B 和 C 的方法是读取 C 的内容并使用路径 /A/B 和 /A/C 访问 B 和 C。但是想在没有路径的情况下直接从 A 中的引用访问 B 和 C

【问题讨论】:

  • 那么您的问题到底是什么?
  • 我想我在这里得到了答案stackoverflow.com/questions/7035733/… 在这一行“或者,您可以在输入目录时 chdir 进入目录,然后在完成后 chdir 备份”

标签: c linux file filesystems traversal


【解决方案1】:

您可以通过使用openatfdopendir 而不是opendir 来遍历树,从而避免重复的路径查找和chdir 的丑陋(全局状态和非线程安全)。

【讨论】:

    【解决方案2】:

    这里:

    #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

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      相关资源
      最近更新 更多