1 /* dirutil.c ... directory utilities.
2 * C. Scott Ananian <cananian@alumni.princeton.edu>
4 * $Id: dirutil.c,v 1.2 2003/06/17 17:25:47 reink Exp $
14 /* Returned malloc'ed string representing basename */
15 char *basenamex(char *pathname
)
17 char *dup
= strdup(pathname
);
18 char *ptr
= strrchr(stripslash(dup
), '/');
19 if (ptr
== NULL
) return dup
;
25 /* Return malloc'ed string representing directory name (no trailing slash) */
26 char *dirname(char *pathname
)
28 char *dup
= strdup(pathname
);
29 char *ptr
= strrchr(stripslash(dup
), '/');
30 if (ptr
== NULL
) { free(dup
); return strdup("."); }
31 if (ptr
== dup
&& dup
[0] == '/') ptr
++;
36 /* In-place modify a string to remove trailing slashes. Returns arg.
37 * stripslash("/") returns "/";
39 char *stripslash(char *pathname
) {
40 int len
= strlen(pathname
);
41 while (len
> 1 && pathname
[len
- 1] == '/')
42 pathname
[--len
] = '\0';
46 /* ensure dirname exists, creating it if necessary. */
47 int make_valid_path(char *dir
, mode_t mode
)
50 char *tmp
= NULL
, *path
= stripslash(strdup(dir
));
52 if (stat(path
, &st
) == 0) { /* file exists */
53 if (S_ISDIR(st
.st_mode
)) { retval
= 1; goto end
; }
54 else { retval
= 0; goto end
; } /* not a directory. Oops. */
56 /* Directory doesn't exist. Let's make it. */
57 /* Make parent first. */
58 if (!make_valid_path(tmp
= dirname(path
), mode
)) { retval
= 0; goto end
; }
59 /* Now make this 'un. */
60 if (mkdir(path
, mode
) < 0) { retval
= 0; goto end
; }
65 if (tmp
!= NULL
) free(tmp
);
66 if (path
!= NULL
) free(path
);