1

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 ?

mcora
  • 43
  • 5

1 Answers1

1

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);
}
pifor
  • 7,419
  • 2
  • 8
  • 16