Main.POSIXCreatingADirectory


How to use POSIX API's to create a directory:

See the POSIX spec for the primary function used: mkdir()

See the related POSIX headers:

Note also that errno.h, a standard C library function, is also used here.

#include <errno.h>
#include <stat.h>
#include <dirent.h> // Not directly needed here

bool createDirectory(const string& path)
{
  errno = 0;
  int resultCode = mkdir(pathName.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
  if (resultCode == -1)
  {
    int errorCode = errno;
    printf("...result/error codes are [%d/%d] : ", resultCode, errorCode);
    if (errorCode == EEXIST)
    {
       printf("[already exists].\n");
    }
    else
    {
       printf("[potential error]\n");
       return false;
     }
   }
   else if (resultCode == 0)
   {
      printf("...done.\n");
   }
   else
   {
      printf("...unknown error code (> 0)\n");
      return false;
   }
   return true;
}

Reporting and dealing with other kinds of errors are left as an excersize.


Return value

From POSIX: Upon successful completion, mkdir() shall return 0. Otherwise, -1 shall be returned, no directory shall be created, and errno shall be set to indicate the error.

Possible error codes

The mkdir() function SHALL fail if:

  • EEXIST: The named file exists.
  • EEXIST: path might be an existing symbolic link
  • EACCES: Search permission is denied on a component of the path prefix, or write permission is denied on the parent directory of the directory to be created.
  • ELOOP: A loop exists in symbolic links encountered during resolution of the path argument.
  • EMLINK: The link count of the parent directory would exceed {LINK_MAX}.
  • ENAMETOOLONG: The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
  • ENOENT: A component of the path prefix specified by path does not name an existing directory or path is an empty string.
  • ENOSPC: The file system does not contain enough space to hold the contents of the new directory or to extend the parent directory of the new directory.
  • ENOTDIR: A component of the path prefix is not a directory.
  • EROFS: The parent directory resides on a read-only file system.

The mkdir() function MAY fail if:

  • ELOOP: More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
  • ENAMETOOLONG: as a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

See also