+ created_dir = (mkdir (dir, mode) == 0);
+
+ if (!created_dir)
+ {
+ struct stat stats;
+ int saved_errno = errno;
+
+ /* The mkdir and stat calls below may appear to be reversed.
+ They are not. It is important to call mkdir first and then to
+ call stat (to distinguish the three cases) only if mkdir fails.
+ The alternative to this approach is to `stat' each directory,
+ then to call mkdir if it doesn't exist. But if some other process
+ were to create the directory between the stat & mkdir, the mkdir
+ would fail with EEXIST. */
+
+ if (stat (dir, &stats))
+ {
+ error (0, saved_errno, _("cannot create directory %s"),
+ quote (dirpath));
+ fail = 1;
+ }
+ else if (!S_ISDIR (stats.st_mode))
+ {
+ error (0, 0, _("%s exists but is not a directory"), quote (dirpath));
+ fail = 1;
+ }
+ else
+ {
+ /* DIR (aka DIRPATH) already exists and is a directory. */
+ }
+ }
+
+ if (created_dir_p)
+ *created_dir_p = created_dir;
+
+ return fail;
+}