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