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.4 (Berkeley) 05/04/95";
16 #endif /* not lint */
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <unistd.h>
21
22 void usage __P((void));
23
24 int
main(argc,argv)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)
42 usage();
43
44 /*
45 * (1) If string is //, skip steps (2) through (5).
46 * (2) If string consists entirely of slash characters, string
47 * shall be set to a single slash character. In this case,
48 * skip steps (3) through (8).
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 continue;
69 *++p = '\0';
70
71 /*
72 * (4) If there are no slash characters remaining in string,
73 * string shall be set to a single period character. In this
74 * case skip steps (5) through (8).
75 *
76 * (5) If there are any trailing nonslash characters in string,
77 * they shall be removed.
78 */
79 while (--p >= *argv)
80 if (*p == '/')
81 break;
82 ++p;
83 if (p == *argv) {
84 (void)printf(".\n");
85 exit(0);
86 }
87
88 /*
89 * (6) If the remaining string is //, it is implementation defined
90 * whether steps (7) and (8) are skipped or processed.
91 *
92 * This case has already been handled, as part of steps (1) and (2).
93 */
94
95 /*
96 * (7) If there are any trailing slash characters in string, they
97 * shall be removed.
98 */
99 while (--p >= *argv)
100 if (*p != '/')
101 break;
102 ++p;
103
104 /*
105 * (8) If the remaining string is empty, string shall be set to
106 * a single slash character.
107 */
108 *p = '\0';
109 (void)printf("%s\n", p == *argv ? "/" : *argv);
110 exit(0);
111 }
112
113 void
usage()114 usage()
115 {
116
117 (void)fprintf(stderr, "usage: dirname path\n");
118 exit(1);
119 }
120