9base

revived minimalist port of Plan 9 userland to Unix
git clone git://git.suckless.org/9base
Log | Files | Refs | README | LICENSE

basename.c (605B)


      1 #include <u.h>
      2 #include <libc.h>
      3 
      4 void
      5 main(int argc, char *argv[])
      6 {
      7 	char *pr;
      8 	int n, dflag;
      9 
     10 	dflag = 0;
     11 	if(argc>1 && strcmp(argv[1], "-d") == 0){
     12 		--argc;
     13 		++argv;
     14 		dflag = 1;
     15 	}
     16 	if(argc < 2 || argc > 3){
     17 		fprint(2, "usage: basename [-d] string [suffix]\n");
     18 		exits("usage");
     19 	}
     20 	pr = utfrrune(argv[1], '/');
     21 	if(dflag){
     22 		if(pr){
     23 			*pr = 0;
     24 			print("%s\n", argv[1]);
     25 			exits(0);
     26 		}
     27 		print(".\n");
     28 		exits(0);
     29 	}
     30 	if(pr)
     31 		pr++;
     32 	else
     33 		pr = argv[1];
     34 	if(argc==3){
     35 		n = strlen(pr)-strlen(argv[2]);
     36 		if(n >= 0 && !strcmp(pr+n, argv[2]))
     37 			pr[n] = 0;
     38 	}
     39 	print("%s\n", pr);
     40 	exits(0);
     41 }