xpg_basename.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* Return basename of given pathname according to the weird XPG specification.
  2. Copyright (C) 1997-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, see
  15. <http://www.gnu.org/licenses/>. */
  16. #include <string.h>
  17. #include <libgen.h>
  18. char *
  19. __xpg_basename (char *filename)
  20. {
  21. char *p;
  22. if (filename == NULL || filename[0] == '\0')
  23. /* We return a pointer to a static string containing ".". */
  24. p = (char *) ".";
  25. else
  26. {
  27. p = strrchr (filename, '/');
  28. if (p == NULL)
  29. /* There is no slash in the filename. Return the whole string. */
  30. p = filename;
  31. else
  32. {
  33. if (p[1] == '\0')
  34. {
  35. /* We must remove trailing '/'. */
  36. while (p > filename && p[-1] == '/')
  37. --p;
  38. /* Now we can be in two situations:
  39. a) the string only contains '/' characters, so we return
  40. '/'
  41. b) p points past the last component, but we have to remove
  42. the trailing slash. */
  43. if (p > filename)
  44. {
  45. *p-- = '\0';
  46. while (p > filename && p[-1] != '/')
  47. --p;
  48. }
  49. else
  50. /* The last slash we already found is the right position
  51. to return. */
  52. while (p[1] != '\0')
  53. ++p;
  54. }
  55. else
  56. /* Go to the first character of the name. */
  57. ++p;
  58. }
  59. }
  60. return p;
  61. }