src/world/usr.bin/basename/src/basename.c

73 lines
2.1 KiB
C

/*
*----------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <jeang3nie@HitchHiker-Linux.org> wrote this file. As long as you
* retain this notice you can do whatever you want with this stuff. If
* we meet some day, and you think this stuff is worth it, you can buy
* me a beer in return.
* ---------------------------------------------------------------------
* ______ _______ _ _________
* ( __ \ ( ___ )( ( /|( )\__ __/
* | ( \ )| ( ) || \ ( ||/ ) (
* | | ) || | | || \ | | | |
* | | | || | | || (\ \) | | |
* | | ) || | | || | \ | | |
* | (__/ )| (___) || ) \ | | |
* (______/ (_______)|/ )_) )_(
*
* _______ _______ _ _________ _______
* ( ____ )( ___ )( \ /|\__ __/( ____ \
* | ( )|| ( ) || \ ( | ) ( | ( |/
* | (____)|| (___) || \ | | | | | |
* | _____)| ___ || (\ \) | | | | |
* | ( | ( ) || | \ | | | | |
* | ) | ) ( || ) \ |___) (___| (____|\
* |/ |/ \||/ \_)\_______/(_______/
*
*/
#define _XOPEN_SOURCE
#include <err.h> // err
#include <libgen.h> // basename
#include <stdio.h> // fprintf, puts
#include <stdlib.h> // exit
#include <string.h> // strlen, strcmp
#include <unistd.h> // getopt
static const char *__progname;
static void usage() {
fprintf(stderr, "usage: %s string [suffix]\n", __progname);
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[]) {
int c;
__progname = basename(argv[0]);
if (argc < 2 || argc > 3)
usage();
while ((c = getopt(argc, argv, "")) != -1)
switch (c) {
case '?':
default:
usage();
}
char *base;
int sufflen;
if ((base = basename(argv[optind])) == NULL)
err(1, "%s", argv[optind]);
if (argc == 3) {
sufflen = strlen(base) - strlen(argv[optind + 1]);
if (sufflen > 0 && !strcmp(base + sufflen, argv[optind + 1]))
base[sufflen] = '\0';
}
puts(base);
exit(EXIT_SUCCESS);
}