basename.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini basename implementation for busybox
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  8. *
  9. */
  10. /* BB_AUDIT SUSv3 compliant */
  11. /* http://www.opengroup.org/onlinepubs/007904975/utilities/basename.html */
  12. /* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
  13. *
  14. * Changes:
  15. * 1) Now checks for too many args. Need at least one and at most two.
  16. * 2) Don't check for options, as per SUSv3.
  17. * 3) Save some space by using strcmp(). Calling strncmp() here was silly.
  18. */
  19. #include "libbb.h"
  20. /* This is a NOFORK applet. Be very careful! */
  21. int basename_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  22. int basename_main(int argc, char **argv)
  23. {
  24. size_t m, n;
  25. char *s;
  26. if (((unsigned int)(argc-2)) >= 2) {
  27. bb_show_usage();
  28. }
  29. /* It should strip slash: /abc/def/ -> def */
  30. s = bb_get_last_path_component_strip(*++argv);
  31. m = strlen(s);
  32. if (*++argv) {
  33. n = strlen(*argv);
  34. if ((m > n) && ((strcmp)(s+m-n, *argv) == 0)) {
  35. m -= n;
  36. /*s[m] = '\0'; - redundant */
  37. }
  38. }
  39. /* puts(s) will do, but we can do without stdio this way: */
  40. s[m++] = '\n';
  41. return full_write(STDOUT_FILENO, s, m) != (ssize_t)m;
  42. }