From 097ab82529f56ccf99b492adce94a3acb50af83a Mon Sep 17 00:00:00 2001 From: Bananymous Date: Thu, 5 Dec 2024 08:30:06 +0200 Subject: [PATCH] userspace: Implement `basename` utility --- userspace/programs/CMakeLists.txt | 1 + userspace/programs/basename/CMakeLists.txt | 8 ++++++ userspace/programs/basename/main.cpp | 30 ++++++++++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 userspace/programs/basename/CMakeLists.txt create mode 100644 userspace/programs/basename/main.cpp diff --git a/userspace/programs/CMakeLists.txt b/userspace/programs/CMakeLists.txt index dabff242..ec6ce9ce 100644 --- a/userspace/programs/CMakeLists.txt +++ b/userspace/programs/CMakeLists.txt @@ -1,5 +1,6 @@ set(USERSPACE_PROGRAMS bananfetch + basename cat cat-mmap chmod diff --git a/userspace/programs/basename/CMakeLists.txt b/userspace/programs/basename/CMakeLists.txt new file mode 100644 index 00000000..0db75c99 --- /dev/null +++ b/userspace/programs/basename/CMakeLists.txt @@ -0,0 +1,8 @@ +set(SOURCES + main.cpp +) + +add_executable(basename ${SOURCES}) +banan_link_library(basename libc) + +install(TARGETS basename OPTIONAL) diff --git a/userspace/programs/basename/main.cpp b/userspace/programs/basename/main.cpp new file mode 100644 index 00000000..7f116e27 --- /dev/null +++ b/userspace/programs/basename/main.cpp @@ -0,0 +1,30 @@ +#include +#include +#include + +int usage(const char* argv0, int ret) +{ + FILE* fout = ret ? stderr : stdout; + fprintf(fout, "usage: %s STRING [SUFFIX]\n", argv0); + return ret; +} + +int main(int argc, const char* argv[]) +{ + if (argc != 2 && argc != 3) + return usage(argv[0], 1); + + const char* result = basename(const_cast(argv[1])); + int result_len = strlen(result); + + if (argc == 3) + { + int suffix_len = strlen(argv[2]); + if (result_len >= suffix_len && strcmp(result - suffix_len, argv[2]) == 0) + result_len -= suffix_len; + } + + printf("%.*s\n", result_len, result); + + return 0; +}