]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
path: SCBasename - function to return basename
authorJeff Lucovsky <jeff@lucovsky.org>
Wed, 30 Sep 2020 11:30:34 +0000 (07:30 -0400)
committerVictor Julien <victor@inliniac.net>
Sun, 4 Oct 2020 19:28:22 +0000 (21:28 +0200)
This commit returns the basename of a file, if it exists
in the same way that `basename(1)` works.

src/util-path.c
src/util-path.h

index 26a87af563cc9aa643c8af82a24522231e5f00e1..de2068dd0eec09af5f33579bb8a1a9a8b85e60f8 100644 (file)
 #include "util-debug.h"
 #include "util-path.h"
 
+#ifdef OS_WIN32
+#define DIRECTORY_SEPARATOR '\\'
+#else
+#define DIRECTORY_SEPARATOR '/'
+#endif
+
 /**
  *  \brief Check if a path is absolute
  *
@@ -81,11 +87,6 @@ int PathIsRelative(const char *path)
 TmEcode PathJoin (char *out_buf, uint16_t buf_len, const char *const dir, const char *const fname)
 {
     SCEnter();
-#ifdef OS_WIN32
-#define DIRECTORY_SEPARATOR '\\'
-#else
-#define DIRECTORY_SEPARATOR '/'
-#endif
     uint16_t max_path_len = MAX(buf_len, PATH_MAX);
     int bytes_written = snprintf(out_buf, max_path_len, "%s%c%s", dir, DIRECTORY_SEPARATOR, fname);
     if (bytes_written <= 0) {
@@ -225,3 +226,24 @@ char *SCRealPath(const char *path, char *resolved_path)
     return realpath(path, resolved_path);
 #endif
 }
+
+/*
+ * \brief Return the basename of the provided path.
+ * \param path The path on which to compute the basename
+ *
+ * \retval the basename of the path or NULL if the path lacks a non-leaf
+ */
+const char *SCBasename(const char *path)
+{
+    if (!path || strlen(path) == 0)
+        return NULL;
+
+    char *final = strrchr(path, DIRECTORY_SEPARATOR);
+    if (!final)
+        return path;
+
+    if (*(final + 1) == '\0')
+        return NULL;
+
+    return final + 1;
+}
index 9108f1829d4deddcc8e735db389b8f49a1ba4c76..8030b3adb15f8100a1ebe3eabb75d399cd8edd84 100644 (file)
@@ -40,5 +40,6 @@ bool SCPathExists(const char *path);
 bool SCIsRegularDirectory(const struct dirent *const dir_entry);
 bool SCIsRegularFile(const struct dirent *const dir_entry);
 char *SCRealPath(const char *path, char *resolved_path);
+const char *SCBasename(const char *path);
 
 #endif /* __UTIL_PATH_H__ */