basename: libc function

This commit is contained in:
K. Lange 2018-11-18 09:47:23 +09:00
parent 004dcb79c2
commit 558a273828
3 changed files with 37 additions and 17 deletions

View File

@ -7,6 +7,7 @@
*/ */
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <libgen.h>
int main(int argc, char * argv[]) { int main(int argc, char * argv[]) {
if (argc < 2) { if (argc < 2) {
@ -14,23 +15,7 @@ int main(int argc, char * argv[]) {
return 1; return 1;
} }
char * s = argv[1]; char * c = basename(argv[1]);
char * c = NULL;
do {
while (*s == '/') {
*s = '\0'; s++;
if (!*s) goto _done;
}
c = s;
s = strchr(c,'/');
} while (s);
_done:
if (!c) {
/* Special case */
fprintf(stdout, "/\n");
return 0;
}
if (argc > 2) { if (argc > 2) {
char * suffix = argv[2]; char * suffix = argv[2];

11
base/usr/include/libgen.h Normal file
View File

@ -0,0 +1,11 @@
#pragma once
#include <_cheader.h>
_Begin_C_Header
//extern char * dirname(char * path);
extern char * basename(char * path);
_End_C_Header

24
libc/libgen/basename.c Normal file
View File

@ -0,0 +1,24 @@
#include <libgen.h>
#include <stdlib.h>
#include <string.h>
char * basename(char * path) {
char * s = path;
char * c = NULL;
do {
while (*s == '/') {
*s = '\0'; s++;
if (!*s) goto _done;
}
c = s;
s = strchr(c,'/');
} while (s);
_done:
if (!c) {
return "/";
}
return c;
}