How to create directory using C++ on Linux

The function to create a new directory is not part of the C or C++ standard library. On Linux, this can be done using the mkdir function call.

Using it is pretty easy:

#include <sys/stat.h>

const int dir_err = mkdir("foo", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (-1 == dir_err)
{
    printf("Error creating directory!n");
    exit(1);
}

This creates the new directory with the commonly used permissions set for user, group and others. Note that this does not create parent directories in a path like foo/bar/xyz, so you will have to create such a path one directory at a time.

A dirty alternative is to use the mkdir shell command which can construct parent directories, if needed:

#include <cstdlib>

const int dir_err = system("mkdir -p foo/bar/xyz");
if (-1 == dir_err)
{
    printf("Error creating directory!n");
    exit(1);
}

Note: You can check if a directory path exists using the opendir call.

Tried with: Ubuntu 14.04

2 thoughts on “How to create directory using C++ on Linux”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s