Browse Source

basename: libc function

K. Lange 2 years ago
parent
commit
558a273828
3 changed files with 37 additions and 17 deletions
  1. 2 17
      apps/basename.c
  2. 11 0
      base/usr/include/libgen.h
  3. 24 0
      libc/libgen/basename.c

+ 2 - 17
apps/basename.c

@@ -7,6 +7,7 @@
  */
 #include <stdio.h>
 #include <string.h>
+#include <libgen.h>
 
 int main(int argc, char * argv[]) {
 	if (argc < 2) {
@@ -14,23 +15,7 @@ int main(int argc, char * argv[]) {
 		return 1;
 	}
 
-	char * s = argv[1];
-	char * c = NULL;
-	do {
-		while (*s == '/') {
-			*s = '\0'; s++;
-			if (!*s) goto _done;
-		}
-		c = s;
-		s = strchr(c,'/');
-	} while (s);
-
-_done:
-	if (!c) {
-		/* Special case */
-		fprintf(stdout, "/\n");
-		return 0;
-	}
+	char * c = basename(argv[1]);
 
 	if (argc > 2) {
 		char * suffix = argv[2];

+ 11 - 0
base/usr/include/libgen.h

@@ -0,0 +1,11 @@
+#pragma once
+
+#include <_cheader.h>
+
+_Begin_C_Header
+
+//extern char * dirname(char * path);
+extern char * basename(char * path);
+
+_End_C_Header
+

+ 24 - 0
libc/libgen/basename.c

@@ -0,0 +1,24 @@
+#include <libgen.h>
+#include <stdlib.h>
+#include <string.h>
+
+char * basename(char * path) {
+	char * s = path;
+	char * c = NULL;
+	do {
+		while (*s == '/') {
+			*s = '\0'; s++;
+			if (!*s) goto _done;
+		}
+		c = s;
+		s = strchr(c,'/');
+	} while (s);
+
+_done:
+
+	if (!c) {
+		return "/";
+	}
+
+	return c;
+}