basename.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. //usage:#define basename_trivial_usage
  27. //usage: "FILE [SUFFIX]"
  28. //usage:#define basename_full_usage "\n\n"
  29. //usage: "Strip directory path and .SUFFIX from FILE"
  30. //usage:
  31. //usage:#define basename_example_usage
  32. //usage: "$ basename /usr/local/bin/foo\n"
  33. //usage: "foo\n"
  34. //usage: "$ basename /usr/local/bin/\n"
  35. //usage: "bin\n"
  36. //usage: "$ basename /foo/bar.txt .txt\n"
  37. //usage: "bar"
  38. #include "libbb.h"
  39. /* This is a NOFORK applet. Be very careful! */
  40. int basename_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  41. int basename_main(int argc, char **argv)
  42. {
  43. size_t m, n;
  44. char *s;
  45. if (argv[1] && strcmp(argv[1], "--") == 0) {
  46. argv++;
  47. argc--;
  48. }
  49. if ((unsigned)(argc-2) >= 2) {
  50. bb_show_usage();
  51. }
  52. /* It should strip slash: /abc/def/ -> def */
  53. s = bb_get_last_path_component_strip(*++argv);
  54. m = strlen(s);
  55. if (*++argv) {
  56. n = strlen(*argv);
  57. if ((m > n) && (strcmp(s+m-n, *argv) == 0)) {
  58. m -= n;
  59. /*s[m] = '\0'; - redundant */
  60. }
  61. }
  62. /* puts(s) will do, but we can do without stdio this way: */
  63. s[m++] = '\n';
  64. /* NB: != is correct here: */
  65. return full_write(STDOUT_FILENO, s, m) != (ssize_t)m;
  66. }