basename.c 1017 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. void
  12. main(int argc, char *argv[])
  13. {
  14. char *pr;
  15. int n, dflag;
  16. dflag = 0;
  17. if(argc>1 && strcmp(argv[1], "-d") == 0){
  18. --argc;
  19. ++argv;
  20. dflag = 1;
  21. }
  22. if(argc < 2 || argc > 3){
  23. fprint(2, "usage: basename [-d] string [suffix]\n");
  24. exits("usage");
  25. }
  26. pr = utfrrune(argv[1], '/');
  27. if(dflag){
  28. if(pr){
  29. *pr = 0;
  30. print("%s\n", argv[1]);
  31. exits(0);
  32. }
  33. print(".\n");
  34. exits(0);
  35. }
  36. if(pr)
  37. pr++;
  38. else
  39. pr = argv[1];
  40. if(argc==3){
  41. n = strlen(pr)-strlen(argv[2]);
  42. if(n >= 0 && !strcmp(pr+n, argv[2]))
  43. pr[n] = 0;
  44. }
  45. print("%s\n", pr);
  46. exits(0);
  47. }