File: mkdir_p.c

package info (click to toggle)
account-utils 1.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 836 kB
  • sloc: ansic: 8,789; xml: 1,584; sh: 77; makefile: 10
file content (52 lines) | stat: -rw-r--r-- 943 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// SPDX-License-Identifier: BSD-2-Clause

#include <errno.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>

#include "mkdir_p.h"

int
mkdir_p(const char *path, mode_t mode)
{
  if (path == NULL)
    return -EINVAL;

  if (mkdir(path, mode) == 0)
    return 0;

  if (errno == EEXIST)
    {
      struct stat st;

      /* Check if the existing path is a directory */
      if (stat(path, &st) != 0)
        return -errno;

      /* If not, fail with ENOTDIR */
      if (!S_ISDIR(st.st_mode))
        return -ENOTDIR;

      /* if it is a directory, return */
      return 0;
    }

  /* If it fails for any reason but ENOENT, fail */
  if (errno != ENOENT)
    return -errno;

  char *buf = strdup(path);
  if (buf == NULL)
    return -ENOMEM;

  int r = mkdir_p(dirname(buf), mode);
  free(buf);
  /* if we couldn't create the parent, fail, too */
  if (r < 0)
    return r;

  return mkdir(path, mode);
}