Line | Count | Source (jump to first uncovered line) |
1 | | /* basename.c -- return the last element in a file name |
2 | | |
3 | | Copyright (C) 1990, 1998-2001, 2003-2006, 2009-2025 Free Software |
4 | | 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 3 of the License, or |
9 | | (at your option) 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, see <https://www.gnu.org/licenses/>. */ |
18 | | |
19 | | #include <config.h> |
20 | | |
21 | | #include "dirname.h" |
22 | | |
23 | | #include <string.h> |
24 | | #include "xalloc.h" |
25 | | |
26 | | char * |
27 | | base_name (char const *name) |
28 | 0 | { |
29 | 0 | char const *base = last_component (name); |
30 | 0 | idx_t length; |
31 | 0 | int dotslash_len; |
32 | 0 | if (*base) |
33 | 0 | { |
34 | 0 | length = base_len (base); |
35 | | |
36 | | /* Collapse a sequence of trailing slashes into one. */ |
37 | 0 | length += ISSLASH (base[length]); |
38 | | |
39 | | /* On systems with drive letters, "a/b:c" must return "./b:c" rather |
40 | | than "b:c" to avoid confusion with a drive letter. On systems |
41 | | with pure POSIX semantics, this is not an issue. */ |
42 | 0 | dotslash_len = FILE_SYSTEM_PREFIX_LEN (base) != 0 ? 2 : 0; |
43 | 0 | } |
44 | 0 | else |
45 | 0 | { |
46 | | /* There is no last component, so NAME is a file system root or |
47 | | the empty string. */ |
48 | 0 | base = name; |
49 | 0 | length = base_len (base); |
50 | 0 | dotslash_len = 0; |
51 | 0 | } |
52 | |
|
53 | 0 | char *p = ximalloc (dotslash_len + length + 1); |
54 | 0 | if (dotslash_len) |
55 | 0 | { |
56 | 0 | p[0] = '.'; |
57 | 0 | p[1] = '/'; |
58 | 0 | } |
59 | | |
60 | | /* Finally, copy the basename. */ |
61 | 0 | memcpy (p + dotslash_len, base, length); |
62 | 0 | p[dotslash_len + length] = '\0'; |
63 | 0 | return p; |
64 | 0 | } |