Is it possible to make multi-level directory?

mkdir --parents folder/subfolder/subsubfolder
mkdir -p folder/subfolder/subsubfolder

mkdir -p /dir1/dir2/dir3

Please check the manpage for details:

man mkdir

Something along the lines of:

#include <libgen.h>

// safe
void mkdir_recursive(const char *path)
{
    char *subpath, *fullpath;
    
    fullpath = strdup(path);
    subpath = dirname(fullpath);
    if (strlen(subpath) > 1)
        mkdir_recursive(subpath);
    mkdir(path);
    free(fullpath);
}

or:

#include <string.h>

// only pass a path starting with a trailing slash
// (if path starts with a dot, it will loop and crash)
void mkdir_recursive(const char *path)
{
    char *subpath, *fullpath;
    
    fullpath = strdup(path);
    subpath = basename(fullpath);
    if (strlen(subpath) > 0)
        mkdir_recursive(subpath);
    mkdir(path);
    free(fullpath);
}

The first way should always works. The second way should only work if your path starts with a trailing slash, because it will loop on paths starting with a dot.

Tags:

C

Directory