mkpath() - `mkdir -p' alike in C for UNIX

January 08, 2009 at 07:11 PM | categories: Technical, C, UNIX | View Comments |

Most people are probably familiar with the UNIX utility, mkdir(1). The mkdir utility makes directories (surprise surprise). There is a matching mkdir(2) system call available in the POSIX standard C library. The usage is pretty straightforward - how ever, the command-line executable, mkdir(1), supports a useful option -p to "create intermediate directories as required". Its very convenient to run `mkdir -p' on a long path before copying things or whatever, since you don't have to worry about the directory structure not existing. However, the mkdir(2) library function doesn't support an analogous mode. If you want to recursively create all the intermediate directories in a path in your program, you must implement this yourself. I've used this same function in at least three distinct projects now and so I decided to post the code:

/* Function with behaviour like `mkdir -p'  */
mkpath(const char *s, mode_t mode){
        char *q, *r = NULL, *path = NULL, *up = NULL;
        int rv;

        rv = -1;
        if (strcmp(s, ".") == 0 || strcmp(s, "/") == 0)
                return (0);

        if ((path = strdup(s)) == NULL)
        if ((q = strdup(s)) == NULL)

        if ((r = dirname(q)) == NULL)
                goto out;
        if ((up = strdup(r)) == NULL)

        if ((mkpath(up, mode) == -1) && (errno != EEXIST))
                goto out;

        if ((mkdir(path, mode) == -1) && (errno != EEXIST))
                rv = -1;
                rv = 0;

        if (up != NULL)
        return (rv);
UPDATE 2010-05-19 These are the includes you need:

Niall O'Higgins is an author and software developer. He wrote the O'Reilly book MongoDB and Python. He also develops Strider Open Source Continuous Deployment and offers full-stack consulting services at

Read and Post Comments

« Previous Page