1 /* $OpenBSD: dirname.c,v 1.10 2003/06/17 21:56:23 millert Exp $ */ 2 3 /* 4 * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19 #ifndef lint 20 static char rcsid[] = "$OpenBSD: dirname.c,v 1.10 2003/06/17 21:56:23 millert Exp $"; 21 #endif /* not lint */ 22 23 #include <errno.h> 24 #include <libgen.h> 25 #include <string.h> 26 #include <sys/param.h> 27 28 char * 29 dirname(const char *path) 30 { 31 static char bname[MAXPATHLEN]; 32 register const char *endp; 33 34 /* Empty or NULL string gets treated as "." */ 35 if (path == NULL || *path == '\0') { 36 (void)strlcpy(bname, ".", sizeof bname); 37 return(bname); 38 } 39 40 /* Strip trailing slashes */ 41 endp = path + strlen(path) - 1; 42 while (endp > path && *endp == '/') 43 endp--; 44 45 /* Find the start of the dir */ 46 while (endp > path && *endp != '/') 47 endp--; 48 49 /* Either the dir is "/" or there are no slashes */ 50 if (endp == path) { 51 (void)strlcpy(bname, *endp == '/' ? "/" : ".", sizeof bname); 52 return(bname); 53 } else { 54 do { 55 endp--; 56 } while (endp > path && *endp == '/'); 57 } 58 59 if (endp - path + 2 > sizeof(bname)) { 60 errno = ENAMETOOLONG; 61 return(NULL); 62 } 63 strlcpy(bname, path, endp - path + 2); 64 return(bname); 65 } 66