summaryrefslogtreecommitdiff
path: root/src/basename.c
blob: 25b8b245d945081524982ffc6e57c5d93f8d4a3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <unistd.h>
#include <string.h>
#include <libgen.h>

static int my_write(int fd, const char *s, size_t l)
{
	if (!l) l = strlen(s);
	while (l) {
		ssize_t n = write(fd, s, l);
		if (n<0) return -1;
		s += n; l -= n;
	}
	return 0;
}

int main(int argc, char *argv[])
{
	char *s;
	if ((unsigned)argc - 2 > 1) {
		my_write(2, argv[0], 0);
		my_write(2, ": missing operand\n", 0);
		return 1;
	}
	s = basename(argv[1]);
	if (argc > 2) {
		size_t k = strlen(s);
		size_t l = strlen(argv[2]);
		if (k>l && !strcmp(s+(k-l), argv[2])) s[k-l]=0;
	}
	if (my_write(1, s, 0)<0 || my_write(1, "\n", 1)<0)
		return 1;
	return 0;
}