xref: /plan9/sys/src/ape/cmd/basename.c (revision 027288c8a8763d34db13dc89d8bcd6514dbc2163)
1 #include <stdlib.h>
2 #include <string.h>
3 #include <stdio.h>
4 
5 void
main(int argc,char ** argv)6 main(int argc, char **argv)
7 {
8 	char *f, *b, *s;
9 	int n;
10 
11 	if(argc < 2 || argc > 3){
12 		fprintf(stderr, "Usage: basename string [suffix]\n");
13 		exit(1);
14 	}
15 	s = argv[1];
16 	b = s + strlen(s) - 1;
17 	while(b > s && *b == '/')
18 		b--;
19 	*++b = 0;
20 	if(b == s+1 && s[0] == '/') {
21 		printf("/");
22 		exit(0);
23 	}
24 	/* now b is after last char of string, trailing slashes removed */
25 
26 	for(f = b; f >= s; f--)
27 		if(*f == '/'){
28 			f++;
29 			break;
30 		}
31 	if(f < s)
32 		f = s;
33 
34 	/* now f is first char after last remaining slash, or first char */
35 
36 	if(argc == 3){
37 		n = strlen(argv[2]);
38 		if(n < b-f && strncmp(b-n, argv[2], n) == 0){
39 			b -= n;
40 			*b = 0;
41 		}
42 	}
43 	printf("%s\n", f);
44 	exit(0);
45 }
46