4

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 ?

5
  • 1
    what is the permission & ownership of created testabc2? which user do you run the program ?
    – Raptor
    Oct 31, 2014 at 2:33
  • Running as non root user. I am specifying mode as 0777. Its in the code. Oct 31, 2014 at 2:34
  • 1
    possible duplicate of Recursive mkdir() system call on Unix Oct 31, 2014 at 2:37
  • does the directory testabc1 exist ? Aug 28, 2015 at 9:00
  • @MichaelWalz No it doesn't. Aug 28, 2015 at 18:02

1 Answer 1

6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.