Created
September 24, 2020 17:38
-
-
Save keisukefukuda/bc31f531669f07404919b929270a2b20 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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