diff --git a/lib/path.cpp b/lib/path.cpp index 831bedda408..5cea8c0ba43 100644 --- a/lib/path.cpp +++ b/lib/path.cpp @@ -428,10 +428,18 @@ bool Path::isDirectory(const std::string &path) return file_type(path) == S_IFDIR; } -bool Path::exists(const std::string &path) +bool Path::exists(const std::string &path, bool* isdir) { const auto type = file_type(path); - return type == S_IFREG || type == S_IFDIR; + if (type == S_IFDIR) + { + if (isdir) + *isdir = true; + return true; + } + if (isdir) + *isdir = false; + return type == S_IFREG; } std::string Path::join(const std::string& path1, const std::string& path2) { diff --git a/lib/path.h b/lib/path.h index db22773ed65..56991b1fb17 100644 --- a/lib/path.h +++ b/lib/path.h @@ -195,9 +195,10 @@ class CPPCHECKLIB Path { /** * @brief Checks if a given path exists (i.e. is a file or directory) * @param path Path to be checked + * @param isdir Optional parameter which indicates if the existing path is a directory * @return true if given path exists */ - static bool exists(const std::string &path); + static bool exists(const std::string &path, bool* isdir = nullptr); /** * join 2 paths with '/' separators diff --git a/test/testpath.cpp b/test/testpath.cpp index 2a726d9eeb4..1c022117a0d 100644 --- a/test/testpath.cpp +++ b/test/testpath.cpp @@ -555,13 +555,27 @@ class TestPath : public TestFixture { void exists() const { ScopedFile file("testpath.txt", "", "testpath"); ScopedFile file2("testpath2.txt", ""); + ASSERT_EQUALS(true, Path::exists("testpath")); - ASSERT_EQUALS(true, Path::exists("testpath/testpath.txt")); ASSERT_EQUALS(true, Path::exists("testpath2.txt")); ASSERT_EQUALS(false, Path::exists("testpath2")); - ASSERT_EQUALS(false, Path::exists("testpath/testpath2.txt")); - ASSERT_EQUALS(false, Path::exists("testpath.txt")); + + bool b = false; + + ASSERT_EQUALS(true, Path::exists("testpath", &b)); + ASSERT_EQUALS(true, b); + ASSERT_EQUALS(true, Path::exists("testpath/testpath.txt", &b)); + ASSERT_EQUALS(false, b); + ASSERT_EQUALS(true, Path::exists("testpath2.txt", &b)); + ASSERT_EQUALS(false, b); + + ASSERT_EQUALS(false, Path::exists("testpath2", &b)); + ASSERT_EQUALS(false, b); + ASSERT_EQUALS(false, Path::exists("testpath/testpath2.txt", &b)); + ASSERT_EQUALS(false, b); + ASSERT_EQUALS(false, Path::exists("testpath.txt", &b)); + ASSERT_EQUALS(false, b); } };