1/* Return the name-within-directory of a file name.
2   Copyright (C) 1996-1999, 2000-2002, 2004, 2006 Free Software Foundation, Inc.
3
4   NOTE: The canonical source of this file is maintained with the GNU C Library.
5   Bugs can be reported to bug-glibc@gnu.org.
6
7   This program is free software; you can redistribute it and/or modify it
8   under the terms of the GNU General Public License as published by the
9   Free Software Foundation; either version 2, or (at your option) any
10   later version.
11
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program; if not, write to the Free Software
19   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20   USA.  */
21
22#include <config.h>
23
24/* Specification.  */
25#include "basename.h"
26
27#if !(__GLIBC__ >= 2)
28
29#include <stdio.h>
30#include <assert.h>
31
32#if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__
33  /* Win32, Cygwin, OS/2, DOS */
34# define HAS_DEVICE(P) \
35    ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) \
36     && (P)[1] == ':')
37# define FILE_SYSTEM_PREFIX_LEN(P) (HAS_DEVICE (P) ? 2 : 0)
38# define ISSLASH(C) ((C) == '/' || (C) == '\\')
39#endif
40
41#ifndef FILE_SYSTEM_PREFIX_LEN
42# define FILE_SYSTEM_PREFIX_LEN(Filename) 0
43#endif
44
45#ifndef ISSLASH
46# define ISSLASH(C) ((C) == '/')
47#endif
48
49#ifndef _LIBC
50/* We cannot generally use the name `basename' since XPG defines an unusable
51   variant of the function but we cannot use it.  */
52# undef basename
53# define basename gnu_basename
54#endif
55
56/* In general, we can't use the builtin `basename' function if available,
57   since it has different meanings in different environments.
58   In some environments the builtin `basename' modifies its argument.
59   If NAME is all slashes, be sure to return `/'.  */
60
61char *
62basename (char const *name)
63{
64  char const *base = name += FILE_SYSTEM_PREFIX_LEN (name);
65  int all_slashes = 1;
66  char const *p;
67
68  for (p = name; *p; p++)
69    {
70      if (ISSLASH (*p))
71	base = p + 1;
72      else
73	all_slashes = 0;
74    }
75
76  /* If NAME is all slashes, arrange to return `/'.  */
77  if (*base == '\0' && ISSLASH (*name) && all_slashes)
78    --base;
79
80  /* Make sure the last byte is not a slash.  */
81  assert (all_slashes || !ISSLASH (*(p - 1)));
82
83  return (char *) base;
84}
85
86#endif
87