source: trunk/minix/commands/simple/basename.c@ 9

Last change on this file since 9 was 9, checked in by Mattia Monga, 13 years ago

Minix 3.1.2a

File size: 1.9 KB
Line 
1/* basename - print last part of a path Authors: B. Garfolo & P. Nelson */
2
3/* Basename - print the last part of a path.
4 *
5 * For MINIX -- Conforms to POSIX - P1003.2/D10
6 * Exception -- it ignores the LC environment variables.
7 *
8 * Original MINIX author: Blaine Garfolo
9 * POSIX rewrite author: Philip A. Nelson
10 *
11 * POSIX version - October 20, 1990
12 * Feb 14, 1991: changed rindex to strrchr. (PAN)
13 *
14 */
15
16
17#include <string.h>
18#include <stdlib.h>
19#include <stdio.h>
20
21#define EOS '\0'
22
23_PROTOTYPE(int main, (int argc, char **argv));
24
25int main(argc, argv)
26int argc;
27char *argv[];
28{
29 char *result_string; /* The pointer into argv[1]. */
30 char *temp; /* Used to move around in argv[1]. */
31 int suffix_len; /* Length of the suffix. */
32 int suffix_start; /* Where the suffix should start. */
33
34
35 /* Check for the correct number of arguments. */
36 if ((argc < 2) || (argc > 3)) {
37 fprintf(stderr, "Usage: basename string [suffix] \n");
38 exit(1);
39 }
40
41 /* Check for all /'s */
42 for (temp = argv[1]; *temp == '/'; temp++) /* Move to next char. */
43 ;
44 if (*temp == EOS) {
45 printf("/\n");
46 exit(0);
47 }
48
49 /* Build the basename. */
50 result_string = argv[1];
51
52 /* Find the last /'s */
53 temp = strrchr(result_string, '/');
54
55 if (temp != NULL) {
56 /* Remove trailing /'s. */
57 while ((*(temp + 1) == EOS) && (*temp == '/')) *temp-- = EOS;
58
59 /* Set result_string to last part of path. */
60 if (*temp != '/') temp = strrchr(result_string, '/');
61 if (temp != NULL && *temp == '/') result_string = temp + 1;
62 }
63
64 /* Remove the suffix, if any. */
65 if (argc > 2) {
66 suffix_len = strlen(argv[2]);
67 suffix_start = strlen(result_string) - suffix_len;
68 if (suffix_start > 0)
69 if (strcmp(result_string + suffix_start, argv[2]) == EOS)
70 *(result_string + suffix_start) = EOS;
71 }
72
73 /* Print the resultant string. */
74 printf("%s\n", result_string);
75 return(0);
76}
Note: See TracBrowser for help on using the repository browser.