userspace: Implement `basename` utility

This commit is contained in:
Bananymous 2024-12-05 08:30:06 +02:00
parent ccb603d77f
commit 097ab82529
3 changed files with 39 additions and 0 deletions

View File

@ -1,5 +1,6 @@
set(USERSPACE_PROGRAMS set(USERSPACE_PROGRAMS
bananfetch bananfetch
basename
cat cat
cat-mmap cat-mmap
chmod chmod

View File

@ -0,0 +1,8 @@
set(SOURCES
main.cpp
)
add_executable(basename ${SOURCES})
banan_link_library(basename libc)
install(TARGETS basename OPTIONAL)

View File

@ -0,0 +1,30 @@
#include <libgen.h>
#include <stdio.h>
#include <string.h>
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<char*>(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;
}