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