From 2012591b27cf1a3444f45ba82536cfe5e7ed294f Mon Sep 17 00:00:00 2001 From: Josh Holtrop Date: Wed, 6 Jul 2016 19:40:35 -0400 Subject: [PATCH] add Path::is_file() and Path::is_dir() --- src/core/Path.cc | 23 +++++++++++++++++++++++ src/core/Path.h | 2 ++ test/src/test_Path.cc | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/src/core/Path.cc b/src/core/Path.cc index 366e851..83fa762 100644 --- a/src/core/Path.cc +++ b/src/core/Path.cc @@ -1,4 +1,7 @@ #include "Path.h" +#include +#include +#include std::string Path::dirname(const std::string & s) { @@ -31,3 +34,23 @@ std::string Path::join(const std::string & first, const std::string & second) } return first + "/" + second; } + +bool Path::is_file(const std::string & s) +{ + struct stat st; + if (stat(s.c_str(), &st) != 0) + { + return false; + } + return S_ISREG(st.st_mode); +} + +bool Path::is_dir(const std::string & s) +{ + struct stat st; + if (stat(s.c_str(), &st) != 0) + { + return false; + } + return S_ISDIR(st.st_mode); +} diff --git a/src/core/Path.h b/src/core/Path.h index b21f37a..782eaf7 100644 --- a/src/core/Path.h +++ b/src/core/Path.h @@ -8,6 +8,8 @@ class Path public: static std::string dirname(const std::string & s); static std::string join(const std::string & first, const std::string & second); + static bool is_file(const std::string & s); + static bool is_dir(const std::string & s); }; #endif diff --git a/test/src/test_Path.cc b/test/src/test_Path.cc index 2212905..ffc90a3 100644 --- a/test/src/test_Path.cc +++ b/test/src/test_Path.cc @@ -61,3 +61,35 @@ TEST(Path_join, does_not_add_extra_slash_when_first_path_already_ends_with_one) { EXPECT_EQ("/var/run", Path::join("/var/", "run")); } + + +TEST(Path_is_file, returns_true_for_file) +{ + EXPECT_TRUE(Path::is_file("test/src/test_Path.cc")); +} + +TEST(Path_is_file, returns_false_for_directory) +{ + EXPECT_FALSE(Path::is_file("test")); +} + +TEST(Path_is_file, returns_false_for_nonexistent_path) +{ + EXPECT_FALSE(Path::is_file("non.existent")); +} + + +TEST(Path_is_dir, returns_true_for_directory) +{ + EXPECT_TRUE(Path::is_dir("test/src")); +} + +TEST(Path_is_dir, returns_false_for_file) +{ + EXPECT_FALSE(Path::is_dir("test/src/test_Path.cc")); +} + +TEST(Path_is_dir, returns_false_for_nonexistent_path) +{ + EXPECT_FALSE(Path::is_dir("non.existent")); +}