Statistics
| Branch: | Revision:

root / prex-0.9.0 / usr / lib / libc / gen / basename.c @ 03e9c04a

History | View | Annotate | Download (1.91 KB)

1
/*
2
 * Copyright (c) 1997, 2004 Todd C. Miller <Todd.Miller@courtesan.com>
3
 *
4
 * Permission to use, copy, modify, and distribute this software for any
5
 * purpose with or without fee is hereby granted, provided that the above
6
 * copyright notice and this permission notice appear in all copies.
7
 *
8
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
 */
16

    
17
#include <errno.h>
18
#include <libgen.h>
19
#include <string.h>
20
#include <sys/param.h>
21

    
22
char *
23
basename(const char *path)
24
{
25
        static char bname[MAXPATHLEN];
26
        size_t len;
27
        const char *endp, *startp;
28

    
29
        /* Empty or NULL string gets treated as "." */
30
        if (path == NULL || *path == '\0') {
31
                bname[0] = '.';
32
                bname[1] = '\0';
33
                return (bname);
34
        }
35

    
36
        /* Strip any trailing slashes */
37
        endp = path + strlen(path) - 1;
38
        while (endp > path && *endp == '/')
39
                endp--;
40

    
41
        /* All slashes becomes "/" */
42
        if (endp == path && *endp == '/') {
43
                bname[0] = '/';
44
                bname[1] = '\0';
45
                return (bname);
46
        }
47

    
48
        /* Find the start of the base */
49
        startp = endp;
50
        while (startp > path && *(startp - 1) != '/')
51
                startp--;
52

    
53
        len = endp - startp + 1;
54
        if (len >= sizeof(bname)) {
55
                errno = ENAMETOOLONG;
56
                return (NULL);
57
        }
58
        memcpy(bname, startp, len);
59
        bname[len] = '\0';
60
        return (bname);
61
}