micro-utils/src/bdname.c
2024-07-09 15:43:55 +03:00

58 lines
918 B
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <libgen.h>
static char *bname(char *str, const char *suffix) {
char *base = basename(str);
if (suffix) {
char *ptr = base + strlen(base) - strlen(suffix);
if (!strcmp(ptr, suffix))
*ptr = '\0';
}
return base;
}
int main(int argc, char **argv) {
char *suffix = NULL;
char d_flag = 0;
int opt;
while ((opt = getopt(argc, argv, "s:d")) != -1) {
switch (opt) {
case 'd':
d_flag = 1;
break;
case 's':
suffix = optarg;
break;
default:
puts("bdname [sd] [str]\n\t-s SFX Set suffix\n\t-d Use dirname instead of basename");
return 0;
}
}
argv += optind;
argc -= optind;
if (argc == 0) {
fprintf(stderr, "bdname: missing operand\n");
return 1;
}
char *str = NULL;
if (d_flag)
str = dirname(argv[0]);
else
str = bname(argv[0], suffix);
puts(str);
return 0;
}