From 3af1c4a680838a13f06363687fa76eca0c3a0302 Mon Sep 17 00:00:00 2001 From: Nathan Wagner Date: Mon, 13 Apr 2015 07:41:17 +0000 Subject: [PATCH] added basename implementation --- utils/basename/basename.c | 74 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 utils/basename/basename.c diff --git a/utils/basename/basename.c b/utils/basename/basename.c new file mode 100644 index 0000000..659def2 --- /dev/null +++ b/utils/basename/basename.c @@ -0,0 +1,74 @@ +#include +#include +#include + +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 characters, string shall be + * set to a single 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 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 characters remaining in string, the prefix + * of string up to and including the last 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; +} -- 2.40.0