1157016Sdes/* $OpenBSD: basename.c,v 1.14 2005/08/08 08:05:33 espie Exp $ */ 2126274Sdes 3113908Sdes/* 4157016Sdes * Copyright (c) 1997, 2004 Todd C. Miller <Todd.Miller@courtesan.com> 5113908Sdes * 6124208Sdes * Permission to use, copy, modify, and distribute this software for any 7124208Sdes * purpose with or without fee is hereby granted, provided that the above 8124208Sdes * copyright notice and this permission notice appear in all copies. 9113908Sdes * 10124208Sdes * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11124208Sdes * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12124208Sdes * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13124208Sdes * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14124208Sdes * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15124208Sdes * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16124208Sdes * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17113908Sdes */ 18124208Sdes 19157016Sdes/* OPENBSD ORIGINAL: lib/libc/gen/basename.c */ 20157016Sdes 21113908Sdes#include "includes.h" 22124208Sdes#ifndef HAVE_BASENAME 23162852Sdes#include <errno.h> 24162852Sdes#include <string.h> 25113908Sdes 26113908Sdeschar * 27113908Sdesbasename(const char *path) 28113908Sdes{ 29113908Sdes static char bname[MAXPATHLEN]; 30157016Sdes size_t len; 31157016Sdes const char *endp, *startp; 32113908Sdes 33113908Sdes /* Empty or NULL string gets treated as "." */ 34113908Sdes if (path == NULL || *path == '\0') { 35157016Sdes bname[0] = '.'; 36157016Sdes bname[1] = '\0'; 37157016Sdes return (bname); 38113908Sdes } 39113908Sdes 40157016Sdes /* Strip any trailing slashes */ 41113908Sdes endp = path + strlen(path) - 1; 42113908Sdes while (endp > path && *endp == '/') 43113908Sdes endp--; 44113908Sdes 45157016Sdes /* All slashes becomes "/" */ 46113908Sdes if (endp == path && *endp == '/') { 47157016Sdes bname[0] = '/'; 48157016Sdes bname[1] = '\0'; 49157016Sdes return (bname); 50113908Sdes } 51113908Sdes 52113908Sdes /* Find the start of the base */ 53113908Sdes startp = endp; 54113908Sdes while (startp > path && *(startp - 1) != '/') 55113908Sdes startp--; 56113908Sdes 57157016Sdes len = endp - startp + 1; 58157016Sdes if (len >= sizeof(bname)) { 59113908Sdes errno = ENAMETOOLONG; 60157016Sdes return (NULL); 61113908Sdes } 62157016Sdes memcpy(bname, startp, len); 63157016Sdes bname[len] = '\0'; 64157016Sdes return (bname); 65113908Sdes} 66113908Sdes 67113908Sdes#endif /* !defined(HAVE_BASENAME) */ 68