From 0bb52bae9132daffc8c918b40fa31d08680b356e Mon Sep 17 00:00:00 2001 From: Karel Zak Date: Tue, 2 Jul 2024 11:14:06 +0200 Subject: [PATCH] lib/fileutils: add ul_basename() Unfortunately, the basename() function can be affected by the creativity of different libc authors, resulting in varying behavior across implementations. Instead, use a local implementation to ensure consistency and portability. Signed-off-by: Karel Zak (cherry picked from commit ff8ee29d648111eb222612ad4251e4c3b236a389) --- include/fileutils.h | 1 + lib/fileutils.c | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/include/fileutils.h b/include/fileutils.h index 538eab0b74..6fc93d0db8 100644 --- a/include/fileutils.h +++ b/include/fileutils.h @@ -114,5 +114,6 @@ int ul_copy_file(int from, int to); extern int ul_reopen(int fd, int flags); +extern char *ul_basename(char *path); #endif /* UTIL_LINUX_FILEUTILS */ diff --git a/lib/fileutils.c b/lib/fileutils.c index 7779e10e68..95ee516350 100644 --- a/lib/fileutils.c +++ b/lib/fileutils.c @@ -2,7 +2,7 @@ * This code is in the public domain; do with it what you wish. * * Copyright (C) 2012 Sami Kerola - * Copyright (C) 2012-2020 Karel Zak + * Copyright (C) 2012-2024 Karel Zak */ #include #include @@ -311,3 +311,35 @@ int ul_reopen(int fd, int flags) return open(buf, flags); } + + +/* This is a libc-independent version of basename(), which is necessary to + * maintain functionality across different libc implementations. It was + * inspired by the behavior and implementation of glibc. + */ +char *ul_basename(char *path) +{ + char *p; + + if (!path || !*path) + return (char *) "."; /* ugly, static string */ + + p = strrchr(path, '/'); + if (!p) + return path; /* no '/', return original */ + + if (*(p + 1) != '\0') + return p + 1; /* begin of the name */ + + while (p > path && *(p - 1) == '/') + --p; /* remove tailing '/' */ + + if (p > path) { + *p-- = '\0'; + while (p > path && *(p - 1) != '/') + --p; /* move to the beginning of the name */ + } else while (*(p + 1) != '\0') + ++p; + + return p; +} -- 2.47.2