Ankur Agarwal
Ankur Agarwal

Reputation: 24768

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 ?

Upvotes: 4

Views: 3141

Answers (1)

Andreas Bombe
Andreas Bombe

Reputation: 2470

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".

Upvotes: 6

Related Questions