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 (#7263)
  • Loading branch information
firewave authored Feb 5, 2025
1 parent 7a9fc27 commit cdf9d6d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 6 deletions.
12 changes: 10 additions & 2 deletions lib/path.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
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
20 changes: 17 additions & 3 deletions test/testpath.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
};

Expand Down

0 comments on commit cdf9d6d

Please sign in to comment.