Search code examples
clinuxdirectory

Creating a new directory in C


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?


Solution

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