Skip to content

Commit e22438b

Browse files
committed
Fix the issue on the Android platform where removeDirectory crashes on some devices.
1 parent 3388f57 commit e22438b

1 file changed

Lines changed: 29 additions & 4 deletions

File tree

native/cocos/platform/FileUtils.cpp

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,11 @@
4747
#include "tinydir/tinydir.h"
4848
#include "tinyxml2/tinyxml2.h"
4949

50+
#if (CC_PLATFORM == CC_PLATFORM_ANDROID)
51+
#include <dirent.h>
52+
#include <unistd.h>
53+
#endif
54+
5055
namespace cc {
5156

5257
// Implement DictMaker
@@ -1063,11 +1068,31 @@ bool FileUtils::removeDirectory(const ccstd::string &path) {
10631068
#if (CC_PLATFORM != CC_PLATFORM_ANDROID)
10641069
return nftw(path.c_str(), unlinkCb, 64, FTW_DEPTH | FTW_PHYS) != -1;
10651070
#else
1066-
ccstd::string command = "rm -r ";
1067-
// Path may include space.
1068-
command += "\"" + path + "\"";
1071+
DIR* dir = opendir(path.c_str());
1072+
if (!dir) return false;
1073+
1074+
struct dirent* entry;
1075+
while ((entry = readdir(dir)) != nullptr) {
1076+
// 跳过 . 和 ..
1077+
if (strcmp(entry->d_name, ".") == 0 ||
1078+
strcmp(entry->d_name, "..") == 0) {
1079+
continue;
1080+
}
1081+
1082+
const std::string fullPath = path + "/" + entry->d_name;
1083+
1084+
if (entry->d_type == DT_DIR) {
1085+
// remove sub directory
1086+
removeDirectory(fullPath);
1087+
} else {
1088+
// remove file
1089+
unlink(fullPath.c_str());
1090+
}
1091+
}
1092+
closedir(dir);
10691093

1070-
return (system(command.c_str()) >= 0);
1094+
// remove empty directory
1095+
return rmdir(path.c_str()) == 0;
10711096
#endif // (CC_PLATFORM != CC_PLATFORM_ANDROID)
10721097
}
10731098

0 commit comments

Comments
 (0)