diff --git a/src/file_utils.cpp b/src/file_utils.cpp index 8543cc5..de697f3 100644 --- a/src/file_utils.cpp +++ b/src/file_utils.cpp @@ -100,11 +100,32 @@ bool mkdir_for_file(const char *filename, __mode_t mode) { return true; } -const char *get_ext(const char *filename) { - const char *p = strrchr(filename, '.'); +static const char* get_filename(const char* path) { + if (path == nullptr) { + return nullptr; + } + const char* p = strrchr(path, '/'); + if (p == nullptr) { + p = strrchr(path, '\\'); + } if (p) { return p + 1; } else { - return ""; + return path; + } +} + +const char *get_ext(const char *path) { + const char* filename = get_filename(path); + if (filename != nullptr) { + const char* p = strrchr(filename, '.'); + if (p) { + return p + 1; + } + else { + return ""; + } + } else { + return nullptr; } } \ No newline at end of file diff --git a/src/file_utils.h b/src/file_utils.h index b8e92d8..a1053a9 100644 --- a/src/file_utils.h +++ b/src/file_utils.h @@ -9,4 +9,4 @@ bool remove_test_file(const char* path); bool get_file_size(const char *name, size_t &size); bool touch(const std::string& pathname); bool mkdir_for_file(const char* filename, __mode_t mode); -const char* get_ext(const char* filename); \ No newline at end of file +const char* get_ext(const char* path); \ No newline at end of file diff --git a/tests/FileUtils_Test.cpp b/tests/FileUtils_Test.cpp index 5f171bd..aa14efd 100644 --- a/tests/FileUtils_Test.cpp +++ b/tests/FileUtils_Test.cpp @@ -22,3 +22,16 @@ TEST(FileUtils, FileNotExistsInvalid) { EXPECT_FALSE(is_file_exists(TEST_FILE_INVALID)); EXPECT_FALSE(is_file_exists("../../../../../../../../../some_file.txt")); } + +TEST(FileUtils, GetExt) { + remove(TEST_FILE); + EXPECT_STREQ(nullptr, get_ext(NULL)); + EXPECT_STREQ("", get_ext("")); + EXPECT_STREQ("", get_ext("filename")); + EXPECT_STREQ("ext", get_ext("filename.ext")); + EXPECT_STREQ("ext", get_ext("dir/filename.ext")); + EXPECT_STREQ("ext", get_ext("dir\\filename.ext")); + EXPECT_STREQ("", get_ext("dir/filename")); + EXPECT_STREQ("", get_ext("dir.ext/filename")); + EXPECT_STREQ("", get_ext("dir.ext\\filename")); +}