basename.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 source tree.
  8. */
  9. /* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
  10. *
  11. * Changes:
  12. * 1) Now checks for too many args. Need at least one and at most two.
  13. * 2) Don't check for options, as per SUSv3.
  14. * 3) Save some space by using strcmp(). Calling strncmp() here was silly.
  15. */
  16. /* BB_AUDIT SUSv3 compliant */
  17. /* http://www.opengroup.org/onlinepubs/007904975/utilities/basename.html */
  18. //kbuild:lib-$(CONFIG_BASENAME) += basename.o
  19. //config:config BASENAME
  20. //config: bool "basename"
  21. //config: default y
  22. //config: help
  23. //config: basename is used to strip the directory and suffix from filenames,
  24. //config: leaving just the filename itself. Enable this option if you wish
  25. //config: to enable the 'basename' utility.
  26. #include "libbb.h"
  27. /* This is a NOFORK applet. Be very careful! */
  28. int basename_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  29. int basename_main(int argc, char **argv)
  30. {
  31. size_t m, n;
  32. char *s;
  33. if ((unsigned)(argc-2) >= 2) {
  34. bb_show_usage();
  35. }
  36. /* It should strip slash: /abc/def/ -> def */
  37. s = bb_get_last_path_component_strip(*++argv);
  38. m = strlen(s);
  39. if (*++argv) {
  40. n = strlen(*argv);
  41. if ((m > n) && (strcmp(s+m-n, *argv) == 0)) {
  42. m -= n;
  43. /*s[m] = '\0'; - redundant */
  44. }
  45. }
  46. /* puts(s) will do, but we can do without stdio this way: */
  47. s[m++] = '\n';
  48. /* NB: != is correct here: */
  49. return full_write(STDOUT_FILENO, s, m) != (ssize_t)m;
  50. }