basename-lgpl.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* basename.c -- return the last element in a file name
  2. Copyright (C) 1990, 1998-2001, 2003-2006, 2009-2023 Free Software
  3. Foundation, Inc.
  4. This file is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as
  6. published by the Free Software Foundation; either version 2.1 of the
  7. License, or (at your option) any later version.
  8. This file 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 Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include "basename-lgpl.h"
  17. #include <string.h>
  18. #include "filename.h"
  19. char *
  20. last_component (char const *name)
  21. {
  22. char const *base = name + FILE_SYSTEM_PREFIX_LEN (name);
  23. char const *p;
  24. bool last_was_slash = false;
  25. while (ISSLASH (*base))
  26. base++;
  27. for (p = base; *p; p++)
  28. {
  29. if (ISSLASH (*p))
  30. last_was_slash = true;
  31. else if (last_was_slash)
  32. {
  33. base = p;
  34. last_was_slash = false;
  35. }
  36. }
  37. return (char *) base;
  38. }
  39. size_t
  40. base_len (char const *name)
  41. {
  42. size_t len;
  43. size_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
  44. for (len = strlen (name); 1 < len && ISSLASH (name[len - 1]); len--)
  45. continue;
  46. if (DOUBLE_SLASH_IS_DISTINCT_ROOT && len == 1
  47. && ISSLASH (name[0]) && ISSLASH (name[1]) && ! name[2])
  48. return 2;
  49. if (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE && prefix_len
  50. && len == prefix_len && ISSLASH (name[prefix_len]))
  51. return prefix_len + 1;
  52. return len;
  53. }