Creating a new directory in C

Jeegar Patel picture Jeegar Patel · Sep 15, 2011 · Viewed 187.9k times · Source

I want to write a program that checks for the existence of a directory; if that directory does not exist then it creates the directory and a log file inside of it, but if the directory already exists, then it just creates a new log file in that folder.

How would I do this in C with Linux?

Answer

Arnaud Le Blanc picture Arnaud Le Blanc · Sep 15, 2011

Look at stat for checking if the directory exists,

And mkdir, to create a directory.

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

struct stat st = {0};

if (stat("/some/directory", &st) == -1) {
    mkdir("/some/directory", 0700);
}

You can see the manual of these functions with the man 2 stat and man 2 mkdir commands.