1/* dirutil.c ... directory utilities. 2 * C. Scott Ananian <cananian@alumni.princeton.edu> 3 * 4 * $Id: dirutil.c,v 1.2 2003/06/17 17:25:47 reink Exp $ 5 */ 6 7#include <sys/stat.h> 8#include <sys/types.h> 9#include <unistd.h> 10#include <string.h> 11#include <stdlib.h> 12#include "dirutil.h" 13 14#ifdef CODE_IN_USE //Winster Chan added 05/16/2006 15/* Returned malloc'ed string representing basename */ 16char *basenamex(char *pathname) 17{ 18 char *dup = strdup(pathname); 19 char *ptr = strrchr(stripslash(dup), '/'); 20 if (ptr == NULL) return dup; 21 ptr = strdup(ptr+1); 22 free(dup); 23 return ptr; 24} 25#endif //CODE_IN_USE Winster Chan added 05/16/2006 26 27/* Return malloc'ed string representing directory name (no trailing slash) */ 28char *dirname(char *pathname) 29{ 30 char *dup = strdup(pathname); 31 char *ptr = strrchr(stripslash(dup), '/'); 32 if (ptr == NULL) { free(dup); return strdup("."); } 33 if (ptr == dup && dup[0] == '/') ptr++; 34 *ptr = '\0'; 35 return dup; 36} 37 38/* In-place modify a string to remove trailing slashes. Returns arg. 39 * stripslash("/") returns "/"; 40 */ 41char *stripslash(char *pathname) { 42 int len = strlen(pathname); 43 while (len > 1 && pathname[len - 1] == '/') 44 pathname[--len] = '\0'; 45 return pathname; 46} 47 48/* ensure dirname exists, creating it if necessary. */ 49int make_valid_path(char *dir, mode_t mode) 50{ 51 struct stat st; 52 char *tmp = NULL, *path = stripslash(strdup(dir)); 53 int retval; 54 if (stat(path, &st) == 0) { /* file exists */ 55 if (S_ISDIR(st.st_mode)) { retval = 1; goto end; } 56 else { retval = 0; goto end; } /* not a directory. Oops. */ 57 } 58 /* Directory doesn't exist. Let's make it. */ 59 /* Make parent first. */ 60 if (!make_valid_path(tmp = dirname(path), mode)) { retval = 0; goto end; } 61 /* Now make this 'un. */ 62 if (mkdir(path, mode) < 0) { retval = 0; goto end; } 63 /* Success. */ 64 retval = 1; 65 66end: 67 if (tmp != NULL) free(tmp); 68 if (path != NULL) free(path); 69 return retval; 70} 71