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