【问题标题】:get root directory in any operating sytem在任何操作系统中获取根目录
【发布时间】:2020-07-16 14:37:07
【问题描述】:

有什么方法可以让 DIR 指针指向根目录,不管是什么操作系统?最好没有像#ifdef _WIN32 #endif (etc..) 这样的宏检查,例如在windows中指向C/文件夹的指针将被返回。

【问题讨论】:

  • 也许某种循环打开.. 直到opendir() 返回NULL
  • /在Unixfike系统上的父目录也是/。经典上,/./.. 的inode 数都是2(值应该是一样的,不管它实际上是不是2)。

标签: c directory operating-system filesystems c89


【解决方案1】:

有没有什么办法可以得到指向根目录的DIR指针,没有 不管什么操作系统?最好没有宏 像这样检查#ifdef _WIN32 #endif (etc..),例如在 将返回指向 C/ 文件夹的 windows 指针。

这个问题假设有一个单一文件系统根的通用概念。不是这种情况。特别是 Windows 是一个多根文件系统,每个驱动器号都有一个单独的根,而且,没有绝对意义上的主驱动器(Windows 的系统文件不一定在 C: 驱动器上)。事实上,支持 C 语言的操作系统根本不需要分层文件系统。

总的来说,文件名字符串的解释传递给fopen()opendir(),& co。是依赖于实现的,所以不,该语言没有提供将DIR * 获取到文件系统根目录的通用方法,即使在该概念首先有意义的系统上也是如此。这是一个很好的理由来重新考虑你为什么认为你想要这样的东西——无论你认为你会用它做什么都可能不像你想象的那么普遍。

【讨论】:

    【解决方案2】:

    我不使用 Windows,所以我不确定这个答案是否可以像 opendir("/") 一样简单,或者以下代码是否可以在 Windows 上正常工作。但是,假设 /.. 在 Windows 上工作,并且 C:/.. 返回 NULL,下面应该打印根目录中的所有项目。

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <string.h>
    #include <dirent.h>
    
    DIR* _get_root(void) {
        DIR     *d = NULL, *prev = NULL;
        char    *path = malloc(strlen(".") + 1);
        char    *pdir = "/..";
    
        strcpy(path, ".");
    
        do {
            if (prev) {
                closedir(prev);
            }
            prev = d;
    
            path = realloc(path, strlen(path) + strlen(pdir) + 1);
            strcat(path, pdir);
    
            d = opendir(path);
        } while (d);
    
        free(path);
        return prev;
    }
    
    int main(int argc, char **argv) {
        DIR             *root = _get_root();
        struct dirent   *sub;
    
        while ((sub = readdir(root))) {
            printf("%s\n", sub->d_name);
        }
    
        closedir(root);
        return 0;
    }
    

    当然,在你使用这个建议之前,试试简单的

    DIR *root = opendir("/");
    

    在 Windows 上看看它是否有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 2012-04-18
      • 1970-01-01
      • 2011-09-02
      • 2017-09-15
      • 2017-11-16
      • 1970-01-01
      相关资源
      最近更新 更多