PageRenderTime 36ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/commands/basename/basename.c

http://www.minix3.org/
C | 76 lines | 40 code | 15 blank | 21 comment | 22 complexity | a4a3aad08f0356673d38ff4da76be533 MD5 | raw file
Possible License(s): MIT, WTFPL, AGPL-1.0, BSD-3-Clause, GPL-3.0, LGPL-2.0, JSON, 0BSD
  1. /* basename - print last part of a path Authors: B. Garfolo & P. Nelson */
  2. /* Basename - print the last part of a path.
  3. *
  4. * For MINIX -- Conforms to POSIX - P1003.2/D10
  5. * Exception -- it ignores the LC environment variables.
  6. *
  7. * Original MINIX author: Blaine Garfolo
  8. * POSIX rewrite author: Philip A. Nelson
  9. *
  10. * POSIX version - October 20, 1990
  11. * Feb 14, 1991: changed rindex to strrchr. (PAN)
  12. *
  13. */
  14. #include <string.h>
  15. #include <stdlib.h>
  16. #include <stdio.h>
  17. #define EOS '\0'
  18. int main(int argc, char **argv);
  19. int main(argc, argv)
  20. int argc;
  21. char *argv[];
  22. {
  23. char *result_string; /* The pointer into argv[1]. */
  24. char *temp; /* Used to move around in argv[1]. */
  25. int suffix_len; /* Length of the suffix. */
  26. int suffix_start; /* Where the suffix should start. */
  27. /* Check for the correct number of arguments. */
  28. if ((argc < 2) || (argc > 3)) {
  29. fprintf(stderr, "Usage: basename string [suffix] \n");
  30. exit(1);
  31. }
  32. /* Check for all /'s */
  33. for (temp = argv[1]; *temp == '/'; temp++) /* Move to next char. */
  34. ;
  35. if (*temp == EOS) {
  36. printf("/\n");
  37. exit(0);
  38. }
  39. /* Build the basename. */
  40. result_string = argv[1];
  41. /* Find the last /'s */
  42. temp = strrchr(result_string, '/');
  43. if (temp != NULL) {
  44. /* Remove trailing /'s. */
  45. while ((*(temp + 1) == EOS) && (*temp == '/')) *temp-- = EOS;
  46. /* Set result_string to last part of path. */
  47. if (*temp != '/') temp = strrchr(result_string, '/');
  48. if (temp != NULL && *temp == '/') result_string = temp + 1;
  49. }
  50. /* Remove the suffix, if any. */
  51. if (argc > 2) {
  52. suffix_len = strlen(argv[2]);
  53. suffix_start = strlen(result_string) - suffix_len;
  54. if (suffix_start > 0)
  55. if (strcmp(result_string + suffix_start, argv[2]) == EOS)
  56. *(result_string + suffix_start) = EOS;
  57. }
  58. /* Print the resultant string. */
  59. printf("%s\n", result_string);
  60. return(0);
  61. }