diff --git a/src/core/Path.cc b/src/core/Path.cc index 1010ad1..6828055 100644 --- a/src/core/Path.cc +++ b/src/core/Path.cc @@ -2,6 +2,7 @@ #include #include #include +#include std::string Path::dirname(const std::string & s) { @@ -54,3 +55,21 @@ bool Path::is_dir(const std::string & s) } return S_ISDIR(st.st_mode); } + +std::shared_ptr>> Path::listdir(const std::string & path) +{ + std::shared_ptr>> result = std::make_shared>>(); + + DIR * dir = opendir(path.c_str()); + if (dir != nullptr) + { + struct dirent * ent; + while ((ent = readdir(dir)) != nullptr) + { + result->push_back(std::make_shared(ent->d_name)); + } + closedir(dir); + } + + return result; +} diff --git a/src/core/Path.h b/src/core/Path.h index 5b43cee..394dcf8 100644 --- a/src/core/Path.h +++ b/src/core/Path.h @@ -2,6 +2,8 @@ #define PATH_H #include +#include +#include class Path { @@ -16,6 +18,7 @@ public: static bool is_file(const std::string & s); static bool is_dir(const std::string & s); + static std::shared_ptr>> listdir(const std::string & path); protected: static std::string _join(const std::string & first, const std::string & second); diff --git a/test/src/test_Path.cc b/test/src/test_Path.cc index c205f92..50d6786 100644 --- a/test/src/test_Path.cc +++ b/test/src/test_Path.cc @@ -1,5 +1,6 @@ #include "gtest/gtest.h" #include "Path.h" +#include TEST(Path_dirname, returns_dot_when_no_directory_component) { @@ -98,3 +99,13 @@ TEST(Path_is_dir, returns_false_for_nonexistent_path) { EXPECT_FALSE(Path::is_dir("non.existent")); } + + +TEST(Path_listdir, returns_list_of_directory_contents) +{ + auto dir_ents = Path::listdir("test"); + EXPECT_NE(dir_ents->end(), std::find_if(dir_ents->begin(), dir_ents->end(), [](std::shared_ptr & s) { return *s == "."; })); + EXPECT_NE(dir_ents->end(), std::find_if(dir_ents->begin(), dir_ents->end(), [](std::shared_ptr & s) { return *s == ".."; })); + EXPECT_NE(dir_ents->end(), std::find_if(dir_ents->begin(), dir_ents->end(), [](std::shared_ptr & s) { return *s == "src"; })); + EXPECT_EQ(dir_ents->end(), std::find_if(dir_ents->begin(), dir_ents->end(), [](std::shared_ptr & s) { return *s == "foo"; })); +}