sbase/basename.c
FRIGN e7c33c4af3 Audit basename(1)
1) be stricter which number of arguments is accepted (1 or 2)
2) basename already returns a pointer to "." is argv[0] is ""
3) No need to check for *p != '/', because basename() only returns
   a string beginning with '/' which has length 1, so if strlen(p)
   == 1, the only way for suffix to be "evaluated" is for off to
   be > 0, being equal to suffix being "", but "" != "/".
4) don't calculate strlen twice for each string. Store it in a
   ssize_t and check if it's > 0.
2015-02-28 14:48:44 +01:00

38 lines
519 B
C

/* See LICENSE file for copyright and license details. */
#include <libgen.h>
#include <stdio.h>
#include <string.h>
#include "util.h"
void
usage(void)
{
eprintf("usage: %s path [suffix]\n", argv0);
}
int
main(int argc, char *argv[])
{
ssize_t off;
char *p;
ARGBEGIN {
default:
usage();
} ARGEND;
if (argc != 1 && argc != 2)
usage();
p = basename(argv[0]);
if (argc == 2) {
off = strlen(p) - strlen(argv[1]);
if (off > 0 && !strcmp(p + off, argv[1]))
p[off] = '\0';
}
puts(p);
return 0;
}