00001 // Copyright (C) 2006-2007 Benedikt Böhm <hollow@gentoo.org> 00002 // 00003 // This program is free software; you can redistribute it and/or 00004 // modify it under the terms of the GNU General Public License 00005 // as published by the Free Software Foundation; either version 2 00006 // of the License, or (at your option) any later version. 00007 // 00008 // This program is distributed in the hope that it will be useful, 00009 // but WITHOUT ANY WARRANTY; without even the implied warranty of 00010 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00011 // GNU General Public License for more details. 00012 // 00013 // You should have received a copy of the GNU General Public License 00014 // along with this program; if not, write to the Free Software 00015 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA 00016 00017 #include "mem.h" 00018 #include "str.h" 00019 00020 char *str_path_basename(const char *path) 00021 { 00022 /* empty string */ 00023 if (str_isempty(path)) 00024 return str_dup("."); 00025 00026 /* skip prefixing '/' */ 00027 while (*path && *path == '/') 00028 path++; 00029 00030 /* string consisting entirely of '/' */ 00031 if (!*path) 00032 return str_dup("/"); 00033 00034 char *p, *buf = str_dup(path); 00035 00036 while ((p = str_rchr(buf, '/', str_len(buf)))) { 00037 /* remove trailing lash */ 00038 if (p[1] == 0 && p != buf) 00039 *p = 0; 00040 00041 /* no trailing slash anymore */ 00042 else 00043 break; 00044 } 00045 00046 char *bn; 00047 00048 /* if a non-trailing slash was found, return everything after it */ 00049 if (p) 00050 bn = str_dup(p + 1); 00051 00052 /* otherwise buf already contains basename */ 00053 else 00054 bn = str_dup(buf); 00055 00056 mem_free(buf); 00057 00058 return bn; 00059 }