Skip to content

Commit cdf9d6d

Browse files
authored
added optional parameter to Path::exists() to indicate if the existing path is a directory (#7263)
1 parent 7a9fc27 commit cdf9d6d

File tree

3 files changed

+29
-6
lines changed

3 files changed

+29
-6
lines changed

lib/path.cpp

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -428,10 +428,18 @@ bool Path::isDirectory(const std::string &path)
428428
return file_type(path) == S_IFDIR;
429429
}
430430

431-
bool Path::exists(const std::string &path)
431+
bool Path::exists(const std::string &path, bool* isdir)
432432
{
433433
const auto type = file_type(path);
434-
return type == S_IFREG || type == S_IFDIR;
434+
if (type == S_IFDIR)
435+
{
436+
if (isdir)
437+
*isdir = true;
438+
return true;
439+
}
440+
if (isdir)
441+
*isdir = false;
442+
return type == S_IFREG;
435443
}
436444

437445
std::string Path::join(const std::string& path1, const std::string& path2) {

lib/path.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,9 +195,10 @@ class CPPCHECKLIB Path {
195195
/**
196196
* @brief Checks if a given path exists (i.e. is a file or directory)
197197
* @param path Path to be checked
198+
* @param isdir Optional parameter which indicates if the existing path is a directory
198199
* @return true if given path exists
199200
*/
200-
static bool exists(const std::string &path);
201+
static bool exists(const std::string &path, bool* isdir = nullptr);
201202

202203
/**
203204
* join 2 paths with '/' separators

test/testpath.cpp

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -555,13 +555,27 @@ class TestPath : public TestFixture {
555555
void exists() const {
556556
ScopedFile file("testpath.txt", "", "testpath");
557557
ScopedFile file2("testpath2.txt", "");
558+
558559
ASSERT_EQUALS(true, Path::exists("testpath"));
559-
ASSERT_EQUALS(true, Path::exists("testpath/testpath.txt"));
560560
ASSERT_EQUALS(true, Path::exists("testpath2.txt"));
561561

562562
ASSERT_EQUALS(false, Path::exists("testpath2"));
563-
ASSERT_EQUALS(false, Path::exists("testpath/testpath2.txt"));
564-
ASSERT_EQUALS(false, Path::exists("testpath.txt"));
563+
564+
bool b = false;
565+
566+
ASSERT_EQUALS(true, Path::exists("testpath", &b));
567+
ASSERT_EQUALS(true, b);
568+
ASSERT_EQUALS(true, Path::exists("testpath/testpath.txt", &b));
569+
ASSERT_EQUALS(false, b);
570+
ASSERT_EQUALS(true, Path::exists("testpath2.txt", &b));
571+
ASSERT_EQUALS(false, b);
572+
573+
ASSERT_EQUALS(false, Path::exists("testpath2", &b));
574+
ASSERT_EQUALS(false, b);
575+
ASSERT_EQUALS(false, Path::exists("testpath/testpath2.txt", &b));
576+
ASSERT_EQUALS(false, b);
577+
ASSERT_EQUALS(false, Path::exists("testpath.txt", &b));
578+
ASSERT_EQUALS(false, b);
565579
}
566580
};
567581

0 commit comments

Comments
 (0)