Skip to content

Commit

Permalink
added optional parameter to Path::exists() to indicate if the exist…
Browse files Browse the repository at this point in the history
…ing path is a directory [skip ci]
  • Loading branch information
firewave committed Jan 27, 2025
1 parent 28edcf7 commit da7169e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
12 changes: 10 additions & 2 deletions lib/path.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -426,10 +426,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) {
Expand Down
3 changes: 2 additions & 1 deletion lib/path.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 10 additions & 1 deletion test/testpath.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -551,13 +551,22 @@ class TestPath : public TestFixture {
void exists() const {
ScopedFile file("testpath.txt", "", "testpath");
ScopedFile file2("testpath2.txt", "");
ASSERT_EQUALS(true, Path::exists("testpath"));

bool b = false;

ASSERT_EQUALS(true, Path::exists("testpath", &b));
ASSERT_EQUALS(true, b);
ASSERT_EQUALS(true, Path::exists("testpath/testpath.txt"));
ASSERT_EQUALS(false, b);
ASSERT_EQUALS(true, Path::exists("testpath2.txt"));
ASSERT_EQUALS(false, b);

ASSERT_EQUALS(false, Path::exists("testpath2"));
ASSERT_EQUALS(false, b);
ASSERT_EQUALS(false, Path::exists("testpath/testpath2.txt"));
ASSERT_EQUALS(false, b);
ASSERT_EQUALS(false, Path::exists("testpath.txt"));
ASSERT_EQUALS(false, b);
}
};

Expand Down

0 comments on commit da7169e

Please sign in to comment.