Search code examples
clinuxoperating-systemfilesystemsmkdir

mkdir -p equivalent in C that creates nested directories recursively


I want to create a new directory inside a new directory. Something like this:

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>

int main() {

    const char * path = "/home/abc/testabc1/testabc2" ;
    mode_t mode = 0777;

    if (mkdir(path, mode) == -1) {

//        printf("Error occurred : %s ", strerror(errno));
        perror("abc");

    }

    else {

        printf("Directory created\n");
    }


}

When I do this I get this error:

abc: No such file or directory

If I remove testabc2 then I am able to create the directory with success. Why so ?


Solution

  • You can only create directories in existing directories. If you want to do the equivalent of mkdir -p you have to do the same thing it does, namely create one directory after another from the top of the path down.

    In your case, that means mkdir of /home/abc/testabc1 before mkdir of /home/abc/testabc1/testabc2.

    Your error message is also misleading since perror("abc"); will prepend any error with "abc:". It has nothing to do with the directory "abc".