tftpd: new applet (mostly using existing code for tftp)
[oweals/busybox.git] / libbb / get_last_path_component.c
index c950faeb35d26a8d5b40a44f57d3d70945265438..0f602157d970ea177d32f8843b995027da4c1532 100644 (file)
@@ -7,24 +7,36 @@
  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  */
 
-char *bb_get_last_path_component(char *path)
+#include "libbb.h"
+/*
+ * "/"        -> "/"
+ * "abc"      -> "abc"
+ * "abc/def"  -> "def"
+ * "abc/def/" -> ""
+ */
+char *bb_get_last_path_component_nostrip(const char *path)
 {
-       char *first = path;
-       char *last;
+       char *slash = strrchr(path, '/');
 
-       last = path - 1;
+       if (!slash || (slash == path && !slash[1]))
+               return (char*)path;
+
+       return slash + 1;
+}
 
-       while (*path) {
-               if ((*path != '/') && (path > ++last)) {
-                       last = first = path;
-               }
-               ++path;
-       }
+/*
+ * "/"        -> "/"
+ * "abc"      -> "abc"
+ * "abc/def"  -> "def"
+ * "abc/def/" -> "def" !!
+ */
+char *bb_get_last_path_component_strip(char *path)
+{
+       char *slash = last_char_is(path, '/');
 
-       if (*first == '/') {
-               last = first;
-       }
-       last[1] = 0;
+       if (slash)
+               while (*slash == '/' && slash != path)
+                       *slash-- = '\0';
 
-       return first;
+       return bb_get_last_path_component_nostrip(path);
 }