]> pd.if.org Git - pdutils/blob - posix/basename/basename.c
rename utils to posix
[pdutils] / posix / basename / basename.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4
5 int main(int ac, char *av[]) {
6         size_t len;
7         char *s, *t;
8
9         s = av[1];
10
11         len = strlen(s);
12
13         /* If string is a null string, it is unspecified whether the resulting
14          * string is '.' or a null string. In either case, skip steps 2 through
15          * 6.
16          */
17         if (len == 0) {
18                 printf("\n");
19                 exit(0);
20         }
21
22         /* 
23          * If string consists entirely of <slash> characters, string shall be
24          * set to a single <slash> character. In this case, skip steps 4 to 6.
25          */
26         while (*s == '/') {
27                 s++;
28                 len--;
29         }
30
31         if (*s == 0) {
32                 printf("/\n");
33                 exit(0);
34         }
35
36         /* If there are any trailing <slash> characters in string, they shall
37          * be removed. */
38         for (t = s+len-1; t > s; t--) {
39                 if (*t != '/') {
40                         break;
41                 }
42                 *t = 0;
43                 len--;
44         }
45
46         /* If there are any <slash> characters remaining in string, the prefix
47          * of string up to and including the last <slash> character in string
48          * shall be removed. */
49         for (t=s+len-1; t > s; t--) {
50                 if (*t == '/') {
51                         s = t+1;
52                         break;
53                 }
54         }
55
56         len = strlen(s);
57         /* If the suffix operand is present, is not identical to the characters
58          * remaining in string, and is identical to a suffix of the characters
59          * remaining in string, the suffix suffix shall be removed from string.
60          * Otherwise, string is not modified by this step. It shall not be
61          * considered an error if suffix is not found in string.
62          */
63         if (ac > 2) {
64                 size_t suflen;
65                 suflen = strlen(av[2]);
66                 if (suflen <= len && !strcmp(av[2], s+len-suflen)) {
67                         len -= suflen;
68                         *(s+len) = 0;
69                 }
70         }
71
72         printf("%s\n", s);
73         return 0;
74 }