summaryrefslogtreecommitdiff
path: root/lib/basename.c
diff options
context:
space:
mode:
authorJim Meyering <jim@meyering.net>1997-06-29 22:25:54 +0000
committerJim Meyering <jim@meyering.net>1997-06-29 22:25:54 +0000
commit04c0cd59a544e18088452ca6ecdbe34163922586 (patch)
tree220ad1a9e4dff999f1a1a6620ebe7502fff6a3c8 /lib/basename.c
parent6ad0d51107d0ead8e5510b3e26c89efa06c20ad7 (diff)
downloadcoreutils-04c0cd59a544e18088452ca6ecdbe34163922586.tar.xz
(base_name_strip_trailing_slashes): new function.
Diffstat (limited to 'lib/basename.c')
-rw-r--r--lib/basename.c68
1 files changed, 68 insertions, 0 deletions
diff --git a/lib/basename.c b/lib/basename.c
index 4087e3dc0..0fd981f30 100644
--- a/lib/basename.c
+++ b/lib/basename.c
@@ -28,3 +28,71 @@ base_name (name)
return (char *) base;
}
+
+#ifdef STDC_HEADERS
+# include <stdlib.h>
+#else
+char *malloc ();
+#endif
+
+char *
+base_name_strip_trailing_slashes (name)
+ char const *name;
+{
+ char const *end_p = name += FILESYSTEM_PREFIX_LEN (name);
+ char const *first, *p;
+ char *base;
+ int length;
+
+ /* Make END_P point to the byte after the last non-slash character
+ in NAME if one exists. */
+ for (p = name; *p; p++)
+ if (!ISSLASH (*p))
+ end_p = p + 1;
+
+ if (end_p == name)
+ {
+ first = end_p;
+ }
+ else
+ {
+ first = end_p - 1;
+ while (first > name && !ISSLASH (*(first - 1)))
+ --first;
+ }
+
+ length = end_p - first;
+ base = (char *) malloc (length + 1);
+ if (base == 0)
+ return 0;
+
+ memcpy (base, first, length);
+ base[length] = '\0';
+
+ return base;
+}
+
+#ifdef TEST
+# include <assert.h>
+# include <stdlib.h>
+
+# define CHECK(a,b) assert (strcmp (base_name_strip_trailing_slashes(a), b) \
+ == 0)
+
+int
+main ()
+{
+ CHECK ("a", "a");
+ CHECK ("ab", "ab");
+ CHECK ("ab/c", "c");
+ CHECK ("/ab/c", "c");
+ CHECK ("/ab/c/", "c");
+ CHECK ("/ab/c////", "c");
+ CHECK ("/", "");
+ CHECK ("////", "");
+ CHECK ("////a", "a");
+ CHECK ("//a//", "a");
+ CHECK ("/a", "a");
+ exit (0);
+}
+#endif