1

From my homework:

Backup files are stored in a hidden directory called .mybackup, which your program creates, if necessary. To create a directory, use the mkdir() function (click here for details), but be sure to check whether the directory already exists (using stat() or checking for EEXIST). If the directory already exists, do not overwrite it.

I thought mkdir inherently returns -1 if the directory already exists. I definitely read that somewhere. Am I mistaken here?

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
  • 1
    I'd suggest checking [this discussion](http://stackoverflow.com/questions/6314042/stat-vs-mkdir-with-eexist) as well: it's not a duplicate, but very close to it. ) – raina77ow Nov 17 '12 at 23:30

2 Answers2

5

mkdir returns -1 for any error. So to distinguish between errors, that is, to discover if the directory already exists, you should either use the stat function or check errno for EEXIST after mkdir returns -1.

if(mkdir(".mybackup", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
{
    if(errno == EEXIST)
    {
        // Directory already exists, do something
    }
}
Toribio
  • 3,963
  • 3
  • 34
  • 48
2

mkdir function can fail for many reasons:

[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.

[EEXIST] The named file exists.

[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}.

If the function returns -1 you can't be sure of which specific error without checking errno, that's why it is suggested.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • +1 for EMLINK, typical user is unlikely to hit this limit on any modern file systems, but these do happen in the field! – Dima Tisnek May 14 '14 at 11:40