]> pd.if.org Git - pdutils/commitdiff
added basename implementation
authorNathan Wagner <nw@hydaspes.if.org>
Mon, 13 Apr 2015 07:41:17 +0000 (07:41 +0000)
committerNathan Wagner <nw@hydaspes.if.org>
Thu, 30 Apr 2015 02:28:43 +0000 (02:28 +0000)
utils/basename/basename.c [new file with mode: 0644]

diff --git a/utils/basename/basename.c b/utils/basename/basename.c
new file mode 100644 (file)
index 0000000..659def2
--- /dev/null
@@ -0,0 +1,74 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+int main(int ac, char *av[]) {
+       size_t len;
+       char *s, *t;
+
+       s = av[1];
+
+       len = strlen(s);
+
+       /* If string is a null string, it is unspecified whether the resulting
+        * string is '.' or a null string. In either case, skip steps 2 through
+        * 6.
+        */
+       if (len == 0) {
+               printf("\n");
+               exit(0);
+       }
+
+       /* 
+        * If string consists entirely of <slash> characters, string shall be
+        * set to a single <slash> character. In this case, skip steps 4 to 6.
+        */
+       while (*s == '/') {
+               s++;
+               len--;
+       }
+
+       if (*s == 0) {
+               printf("/\n");
+               exit(0);
+       }
+
+       /* If there are any trailing <slash> characters in string, they shall
+        * be removed. */
+       for (t = s+len-1; t > s; t--) {
+               if (*t != '/') {
+                       break;
+               }
+               *t = 0;
+               len--;
+       }
+
+       /* If there are any <slash> characters remaining in string, the prefix
+        * of string up to and including the last <slash> character in string
+        * shall be removed. */
+       for (t=s+len-1; t > s; t--) {
+               if (*t == '/') {
+                       s = t+1;
+                       break;
+               }
+       }
+
+       len = strlen(s);
+       /* If the suffix operand is present, is not identical to the characters
+        * remaining in string, and is identical to a suffix of the characters
+        * remaining in string, the suffix suffix shall be removed from string.
+        * Otherwise, string is not modified by this step. It shall not be
+        * considered an error if suffix is not found in string.
+        */
+       if (ac > 2) {
+               size_t suflen;
+               suflen = strlen(av[2]);
+               if (suflen <= len && !strcmp(av[2], s+len-suflen)) {
+                       len -= suflen;
+                       *(s+len) = 0;
+               }
+       }
+
+       printf("%s\n", s);
+       return 0;
+}