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-2020 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 <https://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include "basename-lgpl.h"
  17. #include <stdbool.h>
  18. #include <string.h>
  19. #include "filename.h"
  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 last_was_slash = false;
  26. while (ISSLASH (*base))
  27. base++;
  28. for (p = base; *p; p++)
  29. {
  30. if (ISSLASH (*p))
  31. last_was_slash = true;
  32. else if (last_was_slash)
  33. {
  34. base = p;
  35. last_was_slash = false;
  36. }
  37. }
  38. return (char *) base;
  39. }
  40. size_t
  41. base_len (char const *name)
  42. {
  43. size_t len;
  44. size_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
  45. for (len = strlen (name); 1 < len && ISSLASH (name[len - 1]); len--)
  46. continue;
  47. if (DOUBLE_SLASH_IS_DISTINCT_ROOT && len == 1
  48. && ISSLASH (name[0]) && ISSLASH (name[1]) && ! name[2])
  49. return 2;
  50. if (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE && prefix_len
  51. && len == prefix_len && ISSLASH (name[prefix_len]))
  52. return prefix_len + 1;
  53. return len;
  54. }