xref: /illumos-gate/usr/src/cmd/dirname/dirname.c (revision 711890bc9379ceea66272dc8d4981812224ea86e)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <locale.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <libintl.h>
35 
36 int
37 main(int argc, char **argv)
38 {
39 	char	*p;
40 	char	*string;
41 
42 	/*
43 	 * For better performance, defer the setlocale()/textdomain()
44 	 * calls until they get really required.
45 	 */
46 #if !defined(TEXT_DOMAIN)
47 #define	TEXT_DOMAIN "SYS_TEST"
48 #endif
49 	if (argc == 1) {
50 		(void) puts(".");
51 		return (0);
52 	}
53 	if (strcmp(argv[1], "--") == 0) {
54 		argv++;
55 		argc--;
56 		if (argc == 1) {
57 			(void) puts(".");
58 			return (0);
59 		}
60 	}
61 	if (argc > 2) {
62 		(void) setlocale(LC_ALL, "");
63 		(void) textdomain(TEXT_DOMAIN);
64 		(void) fprintf(stderr, gettext("Usage: dirname [ path ]\n"));
65 		return (1);
66 	}
67 
68 	string = argv[1];
69 
70 	if (*string == '\0') {
71 		(void) puts(".");
72 		return (0);
73 	}
74 
75 	/* remove trailing slashes */
76 	p = string + strlen(string) - 1;
77 	while (p >= string && *p == '/')
78 		*p-- = '\0';
79 
80 	if (*string == '\0') {
81 		/* string contained only slashes */
82 		(void) puts("/");
83 		return (0);
84 	}
85 
86 	/* remove non-slashes */
87 	while (p >= string && *p != '/')
88 		*p-- = '\0';
89 
90 	if (*string == '\0') {
91 		/* string did not begin with a slash */
92 		(void) puts(".");
93 		return (0);
94 	}
95 
96 	/* remove slashes delimiting dirname and basename */
97 	while (p >= string && *p == '/')
98 		*p-- = '\0';
99 
100 	if (*string == '\0') {
101 		/* no dirname part found */
102 		(void) puts("/");
103 		return (0);
104 	}
105 	/* now string points to dirname part */
106 	(void) puts(string);
107 	return (0);
108 }
109