OSDN Git Service

Simplify/unify listfiles recursion: populate directory node (and detect top of tree...
[android-x86/external-toybox.git] / toys / basename.c
1 /* vi: set sw=4 ts=4:
2  *
3  * basename.c - Return non-directory portion of a pathname
4  *
5  * Copyright 2012 Tryn Mirell <tryn@mirell.org>
6  *
7  * See http://opengroup.org/onlinepubs/9699919799/utilities/basename.html
8
9
10 USE_BASENAME(NEWTOY(basename, "<1>2", TOYFLAG_USR|TOYFLAG_BIN))
11
12 config BASENAME
13         bool "basename"
14         default y
15         help
16         usage: basename string [suffix]
17
18         Return non-directory portion of a pathname removing suffix
19 */
20
21 #include "toys.h"
22
23 void basename_main(void)
24 {
25     char *arg = toys.optargs[0], *suffix = toys.optargs[1], *base;
26
27     while ((base = strrchr(arg, '/'))) {
28         if (base == arg) break;
29         if (!base[1]) *base = 0;
30         else {
31             base++;
32             break;
33         }
34     }
35
36     if (!base) base = arg;
37     
38     // chop off the suffix if provided
39     if (suffix) {
40         arg = base + strlen(base) - strlen(suffix);
41         if (arg > base && !strcmp(arg, suffix)) *arg = 0;
42     }
43  
44     puts(base);
45 }