Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <libgen.h>
using namespace std;
char* my_basename(char* str) {
static char* buf = NULL;
static size_t buf_len = 0;
size_t len = strlen(str);
if (len == 0) {
if (buf_len < 2) {
buf = (char*)::realloc(buf, 2);
buf_len = 2;
::strncpy(buf, ".", 2);
}
return buf;
}
if (str[len-1] == '/') {
len--;
}
while (len > 0) {
if (str[len-1] == '/') break;
len--;
}
return str + len ;
}
void test(const char* str, bool verbose=false) {
size_t len = strlen(str);
char* str2 = new char[len + 1];
strncpy(str2, str, len + 1);
std::string input = str;
std::string ref = ::basename(str2);
std::string ans = ::my_basename(str2);
if (ref == ans) {
std::cout << "ok\t" << input << std::endl;
} else {
std::cout << "Bad answer on \"" << input << "\"" << std::endl;
std::cout << "Expected : " << ref << std::endl;
std::cout << "Actual : " << ans << std::endl;
std::cout << "-----------" << std::endl;
}
delete[] str2;
}
int main() {
test("/foo/bar");
test("/foo/bar/");
test("/");
test("test");
test("");
test("..");
test("/..");
test("/../");
test("/./.");
test("/././");
test("./");
test("//");
test("//..");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment