Search code examples
cdirectorytreedirectory-tree

How can I create directory tree in C?


I want an easy way to create multiple directories in C.

For example I want to create directory in:

/a/b/c

but if the directories are not there I want them to be created automagically. How can I do this ?


Solution

  • Here is a small C program to create the directory tree a/b/c in the current directory:

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/stat.h>
    #include <errno.h>
    
    int create_dir(char *name)
    {
        int rc;
    
        rc = mkdir(name, S_IRWXU);
        if (rc != 0 && errno != EEXIST) 
        {
            perror("mkdir");
            exit(1);
        }
        if (rc != 0 && errno == EEXIST)
            printf("%s already exists.\n", name);
    
        return 0;
    }
    
    int main(int argc, char **argv)
    {
    
        create_dir("a");
        create_dir("a/b");
        create_dir("a/b/c");
    
        exit(0);
    }