xref: /netbsd-src/external/gpl2/xcvs/dist/lib/basename.c (revision 5a6c14c844c4c665da5632061aebde7bb2cb5766)
1 /* basename.c -- return the last element in a file name
2 
3    Copyright (C) 1990, 1998, 1999, 2000, 2001, 2003, 2004, 2005 Free
4    Software Foundation, Inc.
5 
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10 
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15 
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software Foundation,
18    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19 #include <sys/cdefs.h>
20 __RCSID("$NetBSD: basename.c,v 1.2 2016/05/17 14:00:09 christos Exp $");
21 
22 
23 #ifdef HAVE_CONFIG_H
24 # include <config.h>
25 #endif
26 
27 #include "dirname.h"
28 #include <string.h>
29 
30 /* In general, we can't use the builtin `basename' function if available,
31    since it has different meanings in different environments.
32    In some environments the builtin `basename' modifies its argument.
33 
34    Return the address of the last file name component of NAME.  If
35    NAME has no file name components because it is all slashes, return
36    NAME if it is empty, the address of its last slash otherwise.  */
37 
38 char *
base_name(char const * name)39 base_name (char const *name)
40 {
41   char const *base = name + FILE_SYSTEM_PREFIX_LEN (name);
42   char const *p;
43 
44   for (p = base; *p; p++)
45     {
46       if (ISSLASH (*p))
47 	{
48 	  /* Treat multiple adjacent slashes like a single slash.  */
49 	  do p++;
50 	  while (ISSLASH (*p));
51 
52 	  /* If the file name ends in slash, use the trailing slash as
53 	     the basename if no non-slashes have been found.  */
54 	  if (! *p)
55 	    {
56 	      if (ISSLASH (*base))
57 		base = p - 1;
58 	      break;
59 	    }
60 
61 	  /* *P is a non-slash preceded by a slash.  */
62 	  base = p;
63 	}
64     }
65 
66   return (char *) base;
67 }
68 
69 /* Return the length of of the basename NAME.  Typically NAME is the
70    value returned by base_name.  Act like strlen (NAME), except omit
71    redundant trailing slashes.  */
72 
73 size_t
base_len(char const * name)74 base_len (char const *name)
75 {
76   size_t len;
77 
78   for (len = strlen (name);  1 < len && ISSLASH (name[len - 1]);  len--)
79     continue;
80 
81   return len;
82 }
83