add Path::listdir()
This commit is contained in:
parent
5df998661b
commit
ff51d17344
@ -2,6 +2,7 @@
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <dirent.h>
|
||||
|
||||
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<std::vector<std::shared_ptr<std::string>>> Path::listdir(const std::string & path)
|
||||
{
|
||||
std::shared_ptr<std::vector<std::shared_ptr<std::string>>> result = std::make_shared<std::vector<std::shared_ptr<std::string>>>();
|
||||
|
||||
DIR * dir = opendir(path.c_str());
|
||||
if (dir != nullptr)
|
||||
{
|
||||
struct dirent * ent;
|
||||
while ((ent = readdir(dir)) != nullptr)
|
||||
{
|
||||
result->push_back(std::make_shared<std::string>(ent->d_name));
|
||||
}
|
||||
closedir(dir);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
@ -2,6 +2,8 @@
|
||||
#define PATH_H
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
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<std::vector<std::shared_ptr<std::string>>> listdir(const std::string & path);
|
||||
|
||||
protected:
|
||||
static std::string _join(const std::string & first, const std::string & second);
|
||||
|
@ -1,5 +1,6 @@
|
||||
#include "gtest/gtest.h"
|
||||
#include "Path.h"
|
||||
#include <algorithm>
|
||||
|
||||
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<std::string> & s) { return *s == "."; }));
|
||||
EXPECT_NE(dir_ents->end(), std::find_if(dir_ents->begin(), dir_ents->end(), [](std::shared_ptr<std::string> & s) { return *s == ".."; }));
|
||||
EXPECT_NE(dir_ents->end(), std::find_if(dir_ents->begin(), dir_ents->end(), [](std::shared_ptr<std::string> & s) { return *s == "src"; }));
|
||||
EXPECT_EQ(dir_ents->end(), std::find_if(dir_ents->begin(), dir_ents->end(), [](std::shared_ptr<std::string> & s) { return *s == "foo"; }));
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user