1 /*- 2 * Copyright (c) 1991, 1993, 1994 3 * The Regents of the University of California. All rights reserved. 4 * 5 * %sccs.include.redist.c% 6 */ 7 8 #ifndef lint 9 static char copyright[] = 10 "@(#) Copyright (c) 1991, 1993, 1994\n\ 11 The Regents of the University of California. All rights reserved.\n"; 12 #endif /* not lint */ 13 14 #ifndef lint 15 static char sccsid[] = "@(#)basename.c 8.4 (Berkeley) 05/04/95"; 16 #endif /* not lint */ 17 18 #include <stdio.h> 19 #include <stdlib.h> 20 #include <string.h> 21 #include <unistd.h> 22 23 void usage __P((void)); 24 25 int 26 main(argc, argv) 27 int argc; 28 char **argv; 29 { 30 char *p; 31 int ch; 32 33 while ((ch = getopt(argc, argv, "")) != EOF) 34 switch(ch) { 35 case '?': 36 default: 37 usage(); 38 } 39 argc -= optind; 40 argv += optind; 41 42 if (argc != 1 && argc != 2) 43 usage(); 44 45 /* 46 * (1) If string is // it is implementation defined whether steps (2) 47 * through (5) are skipped or processed. 48 * 49 * (2) If string consists entirely of slash characters, string shall 50 * be set to a single slash character. In this case, skip steps 51 * (3) through (5). 52 */ 53 for (p = *argv;; ++p) { 54 if (!*p) { 55 if (p > *argv) 56 (void)printf("/\n"); 57 else 58 (void)printf("\n"); 59 exit(0); 60 } 61 if (*p != '/') 62 break; 63 } 64 65 /* 66 * (3) If there are any trailing slash characters in string, they 67 * shall be removed. 68 */ 69 for (; *p; ++p) 70 continue; 71 while (*--p == '/') 72 continue; 73 *++p = '\0'; 74 75 /* 76 * (4) If there are any slash characters remaining in string, the 77 * prefix of string up to an including the last slash character 78 * in string shall be removed. 79 */ 80 while (--p >= *argv) 81 if (*p == '/') 82 break; 83 ++p; 84 85 /* 86 * (5) If the suffix operand is present, is not identical to the 87 * characters remaining in string, and is identical to a suffix 88 * of the characters remaining in string, the suffix suffix 89 * shall be removed from string. 90 */ 91 if (*++argv) { 92 int suffixlen, stringlen, off; 93 94 suffixlen = strlen(*argv); 95 stringlen = strlen(p); 96 97 if (suffixlen < stringlen) { 98 off = stringlen - suffixlen; 99 if (!strcmp(p + off, *argv)) 100 p[off] = '\0'; 101 } 102 } 103 (void)printf("%s\n", p); 104 exit(0); 105 } 106 107 void 108 usage() 109 { 110 111 (void)fprintf(stderr, "usage: basename string [suffix]\n"); 112 exit(1); 113 } 114