source: trunk/libtransmission/basename.c @ 3650

Last change on this file since 3650 was 3650, checked in by charles, 15 years ago

part 1 of the data corruption fix: plug the leaky abstraction in fdlimit

  • Property svn:keywords set to Date Rev Author Id
File size: 1.8 KB
Line 
1/*  $Id: basename.c 3650 2007-10-30 18:35:06Z charles $            */
2/*      $OpenBSD: basename.c,v 1.14 2005/08/08 08:05:33 espie Exp $     */
3
4/*
5 * Copyright (c) 1997, 2004 Todd C. Miller <Todd.Miller@courtesan.com>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#ifndef HAVE_BASENAME
21
22#include <errno.h>
23#include <string.h>
24#include <unistd.h> /* for MAXPATHLEN */
25#include <sys/param.h>
26
27char *
28basename( char * path )
29{
30        static char bname[MAXPATHLEN];
31        size_t len;
32        const char *endp, *startp;
33
34        /* Empty or NULL string gets treated as "." */
35        if (path == NULL || *path == '\0') {
36                bname[0] = '.';
37                bname[1] = '\0';
38                return (bname);
39        }
40
41        /* Strip any trailing slashes */
42        endp = path + strlen(path) - 1;
43        while (endp > path && *endp == '/')
44                endp--;
45
46        /* All slashes becomes "/" */
47        if (endp == path && *endp == '/') {
48                bname[0] = '/';
49                bname[1] = '\0';
50                return (bname);
51        }
52
53        /* Find the start of the base */
54        startp = endp;
55        while (startp > path && *(startp - 1) != '/')
56                startp--;
57
58        len = endp - startp + 1;
59        if (len >= sizeof(bname)) {
60                errno = ENAMETOOLONG;
61                return (NULL);
62        }
63        memcpy(bname, startp, len);
64        bname[len] = '\0';
65        return (bname);
66}
67
68#endif /* HAVE_BASENAME */
Note: See TracBrowser for help on using the repository browser.