summaryrefslogtreecommitdiffstats
path: root/lib/util.c
blob: 6cfcf1f18f1c0ed008ed0ac34ab7ed15d1e87a18 (plain) (blame)
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
#include "log.h"
#include "util.h"

#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>

/* will clobber path */
int vl_mkdir_parents(int fd, char *path, mode_t mode)
{
  int last = 0;

  char *ch = path;
  do {
    if (*ch == '/' || (*ch == '\0' && (last = 1))) {
      /* last is set to 1 iff *ch == '\0' */
      *ch = '\0';

      if (mkdirat(fd, path, mode) < 0 && errno != EEXIST) {
        vl_debug("Failed to create directory %s: %s", path, strerror(errno));
        return -1;
      }

      if (!last) *ch = '/';
    }
  } while (*(ch++));

  return 0;
}