How to use mkdir() from sys/stat.h

Problem:

You want to use the mkdir() function from the sys/stat.h POSIX header, but you don’t know what the mode_t argument should look like.

Solution

For a detailed reference, see the Opengroup page on mkdir

The first argument should be obvious - just enter the path name of the directory you intend to create. If you use a std::string (in C++); use it’s c_str() member function to get a C string.

The second argument defines the permissions the newly created directory shall have. This How-to assumes you’re already familiar with Unix file permissions. If you are not, please read the corresponding Wikipedia Page.

First, decide which rights the directory shall have. This boils down to these 9 questions:

sys/stat.h provides you with several integers you can bytewise-OR (|) together to create your mode_t:

Additionally, some shortcuts are provided (basically a bitwise-OR combination of the above

mkdir("mydir", S_IRUSR | S_IWUSR | S_IXUSR);
mkdir("mydir", S_IRWXU);

In order to grant all rights to everyone (mode 0777 = rwxrwxrwx), you can use any of the following calls equivalently:

mkdir("mydir", S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH);
mkdir("mydir", S_IRWXU | S_IRWXG | S_IRWXO);
mkdir("mydir", ACCESSPERMS);