From: Jeff Lucovsky Date: Wed, 30 Sep 2020 11:30:34 +0000 (-0400) Subject: path: SCBasename - function to return basename X-Git-Tag: suricata-6.0.0~33 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=73567272cd036fa733b3437fa9d455761578492d;p=thirdparty%2Fsuricata.git path: SCBasename - function to return basename This commit returns the basename of a file, if it exists in the same way that `basename(1)` works. --- diff --git a/src/util-path.c b/src/util-path.c index 26a87af563..de2068dd0e 100644 --- a/src/util-path.c +++ b/src/util-path.c @@ -28,6 +28,12 @@ #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; +} diff --git a/src/util-path.h b/src/util-path.h index 9108f1829d..8030b3adb1 100644 --- a/src/util-path.h +++ b/src/util-path.h @@ -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__ */