userspace: Implement `basename` utility
This commit is contained in:
parent
ccb603d77f
commit
097ab82529
|
@ -1,5 +1,6 @@
|
|||
set(USERSPACE_PROGRAMS
|
||||
bananfetch
|
||||
basename
|
||||
cat
|
||||
cat-mmap
|
||||
chmod
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
set(SOURCES
|
||||
main.cpp
|
||||
)
|
||||
|
||||
add_executable(basename ${SOURCES})
|
||||
banan_link_library(basename libc)
|
||||
|
||||
install(TARGETS basename OPTIONAL)
|
|
@ -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;
|
||||
}
|
Loading…
Reference in New Issue