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