Kernel: Copy strrchr, dirname and basename over from libc
This commit is contained in:
parent
1624f0360d
commit
8c0a57f0c2
4
kernel/include/std/libgen.h
Normal file
4
kernel/include/std/libgen.h
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
char* basename(char* path);
|
||||||
|
char* dirname(char* path);
|
@ -20,3 +20,4 @@ int memcmp(const void* a, const void* b, size_t n);
|
|||||||
void* memmove(void* dest, void* src, size_t n);
|
void* memmove(void* dest, void* src, size_t n);
|
||||||
|
|
||||||
char* strdup(const char* src);
|
char* strdup(const char* src);
|
||||||
|
char* strrchr(const char* str, int c);
|
47
kernel/src/std/libgen.cpp
Normal file
47
kernel/src/std/libgen.cpp
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
#include "std/libgen.h"
|
||||||
|
#include "std/string.h"
|
||||||
|
|
||||||
|
static char dot[] = ".";
|
||||||
|
|
||||||
|
char* basename(char* path)
|
||||||
|
{
|
||||||
|
// If path is NULL, or the string's length is 0, return .
|
||||||
|
if (!path) return dot;
|
||||||
|
size_t len = strlen(path);
|
||||||
|
if (!len) return dot;
|
||||||
|
|
||||||
|
// Strip trailing slashes.
|
||||||
|
char* it = path + len - 1;
|
||||||
|
while (*it == '/' && it != path) { it--; }
|
||||||
|
*(it + 1) = 0;
|
||||||
|
if (it == path) return path;
|
||||||
|
|
||||||
|
// Return path from the first character if there are no more slashes, or from the first character after the last
|
||||||
|
// slash.
|
||||||
|
char* beg = strrchr(path, '/');
|
||||||
|
if (!beg) return path;
|
||||||
|
return beg + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char* dirname(char* path)
|
||||||
|
{
|
||||||
|
// If path is NULL, or the string's length is 0, return .
|
||||||
|
if (!path) return dot;
|
||||||
|
size_t len = strlen(path);
|
||||||
|
if (!len) return dot;
|
||||||
|
|
||||||
|
// Strip trailing slashes.
|
||||||
|
char* it = path + len - 1;
|
||||||
|
while (*it == '/' && it != path) { it--; }
|
||||||
|
*(char*)(it + 1) = 0;
|
||||||
|
if (it == path) return path;
|
||||||
|
|
||||||
|
// Search for the last slash. If there is none, return .
|
||||||
|
// Otherwise, we end the string there and return.
|
||||||
|
char* end = strrchr(path, '/');
|
||||||
|
if (!end) return dot;
|
||||||
|
if (end != path) *end = 0;
|
||||||
|
else
|
||||||
|
*(end + 1) = 0;
|
||||||
|
return path;
|
||||||
|
}
|
@ -149,3 +149,11 @@ char* strdup(const char* src)
|
|||||||
memcpy(duplicated, src, length + 1);
|
memcpy(duplicated, src, length + 1);
|
||||||
return duplicated;
|
return duplicated;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
char* strrchr(const char* str, int c)
|
||||||
|
{
|
||||||
|
const char* s = str + strlen(str);
|
||||||
|
while (s != str && *s != (char)c) s--;
|
||||||
|
if (*s == (char)c) return const_cast<char*>(s);
|
||||||
|
return NULL;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user