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