basename-lgpl.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. /* Return the address of the last file name component of NAME. If
  18. NAME has no relative file name components because it is a file
  19. system root, return the empty string. */
  20. char *
  21. last_component (char const *name)
  22. {
  23. char const *base = name + FILE_SYSTEM_PREFIX_LEN (name);
  24. char const *p;
  25. bool saw_slash = false;
  26. while (ISSLASH (*base))
  27. base++;
  28. for (p = base; *p; p++)
  29. {
  30. if (ISSLASH (*p))
  31. saw_slash = true;
  32. else if (saw_slash)
  33. {
  34. base = p;
  35. saw_slash = false;
  36. }
  37. }
  38. return (char *) base;
  39. }
  40. /* Return the length of the basename NAME. Typically NAME is the
  41. value returned by base_name or last_component. Act like strlen
  42. (NAME), except omit all trailing slashes. */
  43. size_t
  44. base_len (char const *name)
  45. {
  46. size_t len;
  47. size_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
  48. for (len = strlen (name); 1 < len && ISSLASH (name[len - 1]); len--)
  49. continue;
  50. if (DOUBLE_SLASH_IS_DISTINCT_ROOT && len == 1
  51. && ISSLASH (name[0]) && ISSLASH (name[1]) && ! name[2])
  52. return 2;
  53. if (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE && prefix_len
  54. && len == prefix_len && ISSLASH (name[prefix_len]))
  55. return prefix_len + 1;
  56. return len;
  57. }