File: mkdirpp.c

package info (click to toggle)
chrony 1.14-7
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,480 kB
  • ctags: 2,091
  • sloc: ansic: 15,266; sh: 194; makefile: 113
file content (118 lines) | stat: -rw-r--r-- 2,060 bytes parent folder | download
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
  $Header: /cvs/src/chrony/mkdirpp.c,v 1.7 1999/08/17 21:24:52 richard Exp $

  =======================================================================

  chronyd/chronyc - Programs for keeping computer clocks accurate.

  Copyright (C) 1997-1999 Richard P. Curnow
  All rights reserved.

  For conditions of use, refer to the file LICENCE.

  =======================================================================

  A function for creating a directory and any parent directories that
  don't exist.

  */

#include "sysincl.h"

#include "mkdirpp.h"

static int
do_dir(char *p)
{
  int status;
  struct stat buf;

  /* See if directory exists */
  status = stat(p, &buf);

  if (status < 0) {
    if (errno == ENOENT) {
      /* Try to create directory */
      status = mkdir(p, 0755);
      return status;
    } else {
      return status;
    }
  }

  if (!S_ISDIR(buf.st_mode)) {
    return -1;
  }

  return 0;
}

/* ================================================== */
/* Return 0 if the directory couldn't be created, 1 if it could (or
   already existed) */

int
mkdir_and_parents(const char *path)
{
  char *p;
  int len;
  int i, j, last;
  len = strlen(path);

  p = (char *) malloc(1 + len);

  i = 1;
  p[0] = path[0]; /* So leading / doesn't trip the next test */
  while (1) {
    p[i] = path[i];
    i++;
    
    if (path[i] == '/' || !path[i]) {
      p[i] = 0;

      if (do_dir(p) < 0) {
        return 0;
      }

      if (!path[i]) {
        /* End of the string */
        break;
      }

      /* check whether its a trailing / or group of / */
      last = 1;
      j = i+1;
      while (path[j]) {
        if (path[j] != '/') {
          last = 0;
          break;
        }
      }

      if (last) {
        break;
      }
    }

    if (!path[i]) break;

  }  

  free(p);
  return 1;

}

/* ================================================== */

#if 0
int main(int argc, char **argv) {
  if (argc > 1) {
    mkdir_and_parents(argv[1]);
    return 0;
  } else {
    return 1;
  }
}
#endif