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