basename.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* basename.c -- return the last element in a file name
  2. Copyright (C) 1990, 1998-2001, 2003-2006, 2009-2013 Free Software
  3. Foundation, Inc.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. #include "dirname.h"
  16. #include <string.h>
  17. #include "xalloc.h"
  18. #include "xstrndup.h"
  19. char *
  20. base_name (char const *name)
  21. {
  22. char const *base = last_component (name);
  23. size_t length;
  24. /* If there is no last component, then name is a file system root or the
  25. empty string. */
  26. if (! *base)
  27. return xstrndup (name, base_len (name));
  28. /* Collapse a sequence of trailing slashes into one. */
  29. length = base_len (base);
  30. if (ISSLASH (base[length]))
  31. length++;
  32. /* On systems with drive letters, "a/b:c" must return "./b:c" rather
  33. than "b:c" to avoid confusion with a drive letter. On systems
  34. with pure POSIX semantics, this is not an issue. */
  35. if (FILE_SYSTEM_PREFIX_LEN (base))
  36. {
  37. char *p = xmalloc (length + 3);
  38. p[0] = '.';
  39. p[1] = '/';
  40. memcpy (p + 2, base, length);
  41. p[length + 2] = '\0';
  42. return p;
  43. }
  44. /* Finally, copy the basename. */
  45. return xstrndup (base, length);
  46. }