basename.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. if (*++argv) {
  32. n = strlen(*argv);
  33. m = strlen(s);
  34. if ((m > n) && ((strcmp)(s+m-n, *argv) == 0)) {
  35. s[m-n] = '\0';
  36. }
  37. }
  38. puts(s);
  39. return fflush(stdout);
  40. }