aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

basename.c (813B)


      1 /* see LICENSE file for copyright and license details */
      2 
      3 #include <libgen.h>
      4 #include <stdio.h>
      5 #include <string.h>
      6 
      7 #include "util.h"
      8 
      9 static void
     10 usage(void)
     11 {
     12   eprintf("usage: %s path [suffix]\n", argv0);
     13 }
     14 
     15 // ?man basename: strip directory and suffix from filenames
     16 // ?man arguments: path [suffix]
     17 // ?man print filename with leading directories and optional suffix removed
     18 int
     19 main(int argc, char *argv[])
     20 {
     21   ssize_t off;
     22   size_t  slen;
     23   char   *p = "";
     24 
     25   ARGBEGIN
     26   {
     27     default:
     28       usage();
     29   }
     30   ARGEND
     31 
     32   if (argc != 1 && argc != 2)
     33     usage();
     34 
     35   if (argv[0][0])
     36     p = basename(argv[0]);
     37   if (argc == 2 && (slen = strlen(argv[1])) > 0) {
     38     off = strlen(p) - slen;
     39     if (off > 0 && !strcmp(p + off, argv[1]))
     40       p[off] = '\0';
     41   }
     42   puts(p);
     43 
     44   return fshut(stdout, "<stdout>");
     45 }