Luna/libluna/src/CPath.cpp

53 lines
1.4 KiB
C++
Raw Normal View History

#include <luna/CPath.h>
#include <luna/CString.h>
static char dot[] = ".";
2023-03-28 17:47:47 +00:00
extern "C"
{
2023-03-28 17:47:47 +00:00
char* basename(char* path)
{
// If path is NULL, or the string's length is 0, return .
if (!path) return dot;
usize len = strlen(path);
if (!len) return dot;
2023-03-28 17:47:47 +00:00
// Strip trailing slashes.
char* it = path + len - 1;
while (*it == '/' && it != path) { it--; }
*(it + 1) = 0;
if (it == path) return path;
2023-03-28 17:47:47 +00:00
// 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;
}
2023-03-28 17:47:47 +00:00
char* dirname(char* path)
{
// If path is NULL, or the string's length is 0, return .
if (!path) return dot;
usize len = strlen(path);
if (!len) return dot;
if (len == 1 && *path != '/') return dot;
2023-03-28 17:47:47 +00:00
// Strip trailing slashes.
char* it = path + len - 1;
while (*it == '/' && it != path) { it--; }
*(char*)(it + 1) = 0;
if (it == path) return path;
2023-03-28 17:47:47 +00:00
// 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;
}
}