Browse Source

dirname: add command and libc function

K. Lange 2 years ago
parent
commit
6a0845d54a
3 changed files with 71 additions and 1 deletions
  1. 22 0
      apps/dirname.c
  2. 1 1
      base/usr/include/libgen.h
  3. 48 0
      libc/libgen/dirname.c

+ 22 - 0
apps/dirname.c

@@ -0,0 +1,22 @@
+/* vim: tabstop=4 shiftwidth=4 noexpandtab
+ * This file is part of ToaruOS and is released under the terms
+ * of the NCSA / University of Illinois License - see LICENSE.md
+ * Copyright (C) 2018 K. Lange
+ *
+ * dirname - print directory name from path string
+ */
+#include <stdio.h>
+#include <string.h>
+#include <libgen.h>
+
+int main(int argc, char * argv[]) {
+	if (argc < 2) {
+		fprintf(stderr, "%s: expected argument\n", argv[0]);
+		return 1;
+	}
+
+	char * c = dirname(argv[1]);
+	fprintf(stdout, "%s\n", c);
+	return 0;
+}
+

+ 1 - 1
base/usr/include/libgen.h

@@ -4,7 +4,7 @@
 
 _Begin_C_Header
 
-//extern char * dirname(char * path);
+extern char * dirname(char * path);
 extern char * basename(char * path);
 
 _End_C_Header

+ 48 - 0
libc/libgen/dirname.c

@@ -0,0 +1,48 @@
+#include <libgen.h>
+#include <stdlib.h>
+#include <string.h>
+
+char * dirname(char * path) {
+	int has_slash = 0;
+	char * c = path;
+	while (*c) {
+		if (*c == '/') {
+			has_slash = 1;
+		}
+		c++;
+	}
+	if (!has_slash) {
+		return ".";
+	}
+
+	c--;
+	while (*c == '/') {
+		*c = '\0';
+		if (c == path) break;
+		c--;
+	}
+
+	if (c == path) {
+		return "/";
+	}
+
+	/* All trailing slashes are cleared out */
+	while (*c != '/') {
+		*c = '\0';
+		if (c == path) break;
+		c--;
+	}
+
+	if (c == path) {
+		if (*c == '/') return "/";
+		return ".";
+	}
+
+	while (*c == '/') {
+		if (c == path) return "/";
+		*c = '\0';
+		c--;
+	}
+
+	return path;
+}