Search code examples
cdirectoryoperating-systemfilesystemsc89

get root directory in any operating sytem


Is there is any way to get the DIR pointer to the root directory, no matter what the operating system? preferably without the macros checking like so #ifdef _WIN32 #endif (etc..) so for example in windows pointer to the C/ folder will be returned.


Solution

  • I don't use Windows, so I'm not sure if this answer could be as simple as opendir("/"), or if the following code will work properly on Windows. However, assuming that /.. works on Windows, and that C:/.. returns NULL, the following should print all of the items in the root directory.

    #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;
    }
    

    Of course, before you use that suggestion, just try the simple

    DIR *root = opendir("/");
    

    on Windows and see if it works.