xref: /titanic_51/usr/src/cmd/basename/basename.c (revision fa9e4066f08beec538e775443c5be79dd423fcab)
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 2004 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 
34 static void output(char *);
35 static void usage(void);
36 
37 int
38 main(int argc, char **argv)
39 {
40 	char	*p;
41 	char	*string;
42 	char	*suffix;
43 
44 	(void) setlocale(LC_ALL, "");
45 #if !defined(TEXT_DOMAIN)
46 #define	TEXT_DOMAIN "SYS_TEST"
47 #endif
48 	(void) textdomain(TEXT_DOMAIN);
49 
50 	if (argc == 1)
51 		output(".");
52 
53 	if (strcmp(argv[1], "--") == 0) {
54 		argv++;
55 		argc--;
56 	}
57 
58 	if (argc == 1)
59 		output(".");
60 
61 	if (argc > 3)
62 		usage();
63 
64 	string = argv[1];
65 	suffix = (argc == 2) ? NULL : argv[2];
66 
67 	if (*string == '\0')
68 		output(".");
69 
70 	/* remove trailing slashes */
71 	p = string + strlen(string) -1;
72 	while ((p >= string) && (*p == '/'))
73 		*p-- = '\0';
74 
75 	if (*string == '\0')
76 		output("/");
77 
78 	/* skip to one past last slash */
79 	if ((p = strrchr(string, '/')) != NULL)
80 		string = p + 1;
81 
82 	/*
83 	 * if a suffix is present and is not the same as the remaining
84 	 * string and is identical to the last characters in the remaining
85 	 * string, remove those characters from the string.
86 	 */
87 	if (suffix != NULL)
88 		if (strcmp(string, suffix) != NULL) {
89 			p = string + strlen(string) - strlen(suffix);
90 			if (strcmp(p, suffix) == NULL)
91 				*p = '\0';
92 		}
93 
94 	output(string);
95 	return (0);
96 }
97 
98 static void
99 output(char *string)
100 {
101 	(void) printf("%s\n", string);
102 	exit(0);
103 }
104 
105 static void usage(void)
106 {
107 	(void) fprintf(stderr,
108 	    gettext("Usage: basename string [ suffix ]\n"));
109 	exit(1);
110 }
111