blob: e7b1a773eb9cfe315901caaa1542b07e37840585 (
plain)
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
|
/* dirutil.c ... directory utilities.
* C. Scott Ananian <cananian@alumni.princeton.edu>
*
* $Id: dirutil.c,v 1.2 2003/06/17 17:25:47 reink Exp $
*/
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include "dirutil.h"
/* Returned malloc'ed string representing basename */
char *basenamex(char *pathname)
{
char *dup = strdup(pathname);
char *ptr = strrchr(stripslash(dup), '/');
if (ptr == NULL) return dup;
ptr = strdup(ptr+1);
free(dup);
return ptr;
}
/* Return malloc'ed string representing directory name (no trailing slash) */
char *dirnamex(char *pathname)
{
char *dup = strdup(pathname);
char *ptr = strrchr(stripslash(dup), '/');
if (ptr == NULL) { free(dup); return strdup("."); }
if (ptr == dup && dup[0] == '/') ptr++;
*ptr = '\0';
return dup;
}
/* In-place modify a string to remove trailing slashes. Returns arg.
* stripslash("/") returns "/";
*/
char *stripslash(char *pathname) {
int len = strlen(pathname);
while (len > 1 && pathname[len - 1] == '/')
pathname[--len] = '\0';
return pathname;
}
/* ensure dirname exists, creating it if necessary. */
int make_valid_path(char *dir, mode_t mode)
{
struct stat st;
char *tmp = NULL, *path = stripslash(strdup(dir));
int retval;
if (stat(path, &st) == 0) { /* file exists */
if (S_ISDIR(st.st_mode)) { retval = 1; goto end; }
else { retval = 0; goto end; } /* not a directory. Oops. */
}
/* Directory doesn't exist. Let's make it. */
/* Make parent first. */
if (!make_valid_path(tmp = dirnamex(path), mode)) { retval = 0; goto end; }
/* Now make this 'un. */
if (mkdir(path, mode) < 0) { retval = 0; goto end; }
/* Success. */
retval = 1;
end:
if (tmp != NULL) free(tmp);
if (path != NULL) free(path);
return retval;
}
|