File system

File system mkdir

int mkdir(const char* pathname, mode_t mode)

#include <sys/stat.h>

bool createDirIfNecessary(const char *path) {
    struct stat statbuf;

    int result = stat(path, &statbuf);
    if (result == 0) {
        if ((statbuf.st_mode & S_IFDIR) != 0) {
  "%s exists and is a directory", path);
            return true;

        Log.error("file in the way, deleting %s", path);
    else {
        if (errno != ENOENT) {
            // Error other than file does not exist
            Log.error("stat filed errno=%d", errno);
            return false;

    // File does not exist (errno == 2)
    result = mkdir(path, 0777);
    if (result == 0) {"created dir %s", path);
        return true;
    else {
        Log.error("mkdir failed errno=%d", errno);
        return false;
  • pathname: The pathname to the file (Unix-style, with forward slash as the directory separator).
  • mode: Mode of the file, currently ignored. For future compatibility, you may want to set this to S_IRWXU | S_IRWXG | S_IRWXO (or 0777).

Create a directory on the file system.

Returns 0 on success. On error, returns -1 and sets errno. Some possible errno values include:

  • EEXIST: Directory already exists, or there is file that already exists with that name.
  • ENOSPC: No space left on the file system to create a directory.

The example code creates a directory if it does not already exists. It takes care of several things:

  • If there is a file with the same name as the directory, it deletes the file.
  • If the directory exists, it does not try to create it.
  • If the directory does not exist, it will be created.
  • It will only create the last directory in the path - it does not create a hierarchy of directories!