Laksith
Laksith

Reputation: 374

How can I check for the existence of a directory in a c program and create it if it isn't there

similar question here.

But it only covers for a single directory level. For example if you gave /home/mypc/directory and if only directory doesn’t exist, it creates one. but when it comes to /home/mypc/directory/directory2 where both directory and directory2 doesn't exist, It gives a segmentation fault error. Could anyone suggest a suitable method for this.

thanks in advance.

Upvotes: 1

Views: 311

Answers (3)

sehe
sehe

Reputation: 392833

If you don't want to depend on external processes, you could just write a recursive function to create a directory hierarchy:

int mkdirhier(char const* target) {
    int r = 0;

    struct stat st = {0};
    if (-1 != stat(target, &st))
        return 0; // already exists

    char* parent = strdup(target);
    if (strcmp(dirname(parent), target))
        r = mkdirhier(parent); // recurse

    if (parent)
        free(parent);

    if (!r && (r = mkdir(target, 0700)))
        perror(target);

    return r;
}

Live On Coliru

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
#include <errno.h>
#include <time.h>

int mkdirhier(char const* target);

int main() {
    char buf[1024];
    srand(time(NULL));

    snprintf(buf, sizeof(buf), "./tree/some%d/dir%d/sub", rand(), rand());
    mkdirhier(buf);

    snprintf(buf, sizeof(buf), "/nopermissions/tree/some%d/dir%d/sub", rand(), rand());
    return mkdirhier(buf);
}

Prints

gcc main.c; ./a.out; find .
/nopermissions: Permission denied
.
./tree
./tree/some1804649601
./tree/some1804649601/dir1553142090
./tree/some1804649601/dir1553142090/sub
./main.cpp
./a.out
./main.c

Upvotes: 6

Lucas Magalh&#227;es
Lucas Magalh&#227;es

Reputation: 145

If you are going to use mkdir to create the directory just add -p.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>

struct stat st = {0};

if (stat("/home/mypc/directory/directory2", &st) == -1) {
    system("mkdir --mode=744 -p /home/mypc/directory/directory2");
}

Upvotes: -1

Some programmer dude
Some programmer dude

Reputation: 409136

Split the path into its components, and check each and every component of the path. So for the path /home/mypc/directory/directory2 you check and possibly create, in order

  1. /home
  2. /home/mypc
  3. /home/mypc/directory
  4. /home/mypc/directory/directory2

Upvotes: 1

Related Questions