Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to create directory using C++ on Linux

📅 2014-Aug-07 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, linux, mkdir ⬩ 📚 Archive

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


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧