From cc6e7a281a3bfb8d4428e8a49aa007cfaf166e83 Mon Sep 17 00:00:00 2001 From: wujianlin Date: Tue, 2 Jul 2024 13:46:31 +0000 Subject: [PATCH] directory_ex.cpp optimization Issue:https://gitee.com/openharmony/commonlibrary_c_utils/issues/IAA2G5?from=project-issue Signed-off-by: wujianlin --- base/src/directory_ex.cpp | 8 +++++++- base/test/unittest/common/utils_directory_test.cpp | 11 +++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/base/src/directory_ex.cpp b/base/src/directory_ex.cpp index 4ddd646..bac6356 100644 --- a/base/src/directory_ex.cpp +++ b/base/src/directory_ex.cpp @@ -140,6 +140,9 @@ string ExcludeTrailingPathDelimiter(const std::string& path) string IncludeTrailingPathDelimiter(const std::string& path) { + if (path.empty()) { + return "/"; + } if (path.rfind("/") != path.size() - 1) { return path + "/"; } @@ -164,7 +167,10 @@ void GetDirFiles(const string& path, vector& files) if (ptr == nullptr) { closedir(topNode); traverseStack.pop(); - currentPath.erase(currentPath.find_last_of("/")); + auto pos = currentPath.find_last_of("/"); + if (pos != string::npos) { + currentPath.erase(pos); + } continue; } diff --git a/base/test/unittest/common/utils_directory_test.cpp b/base/test/unittest/common/utils_directory_test.cpp index 265571b..c806735 100644 --- a/base/test/unittest/common/utils_directory_test.cpp +++ b/base/test/unittest/common/utils_directory_test.cpp @@ -139,6 +139,17 @@ HWTEST_F(UtilsDirectoryTest, testIncludeTrailingPathDelimiter001, TestSize.Level EXPECT_EQ(strResult, strName); } +/* + * @tc.name: testIncludeTrailingPathDelimiter002 + * @tc.desc: directory unit test + */ +HWTEST_F(UtilsDirectoryTest, testIncludeTrailingPathDelimiter002, TestSize.Level0) +{ + string strResult = "/"; + string strName = IncludeTrailingPathDelimiter(""); + EXPECT_EQ(strResult, strName); +} + /* * @tc.name: testGetDirFiles001 * @tc.desc: test GetDirFiles works on multi-level directory -- Gitee