在lua中递归删除一个文件夹
在lua中递归删除一个文件夹 rmdir in quick-cocos2d-x with lua. 在使用 quick-cocos2d-x 做项目热更新的时候,我需要建立临时文件夹以保存下载的更新包。在更新完成后,我需要删除这些临时文件和文件夹。 cocos2d-x 和 quick-cocos2d-x 都没有提供删除文件夹功能。我做了如下2个尝试: 1. 使用C++ 在 cocos2d-x 2.x 中的?AssetsManager?包中提供了一个? bool AssetsManager::createDirectory(const char *path) { #if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) mode_t processMask = umask(0); int ret = mkdir(path,S_IRWXU | S_IRWXG | S_IRWXO); umask(processMask); if (ret != 0 && (errno != EEXIST)) { return false; } return true; #else BOOL ret = CreateDirectoryA(path,NULL); if (!ret && ERROR_ALREADY_EXISTS != GetLastError()) { return false; } return true; #endif } 在 cocos2d-x 2.x 的?AssetsManager sample?范例中提供了一个? void UpdateLayer::reset(cocos2d::CCObject *pSender) { pProgressLabel->setString(" "); // Remove downloaded files #if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) string command = "rm -r "; // Path may include space. command += """ + pathToSave + """; system(command.c_str()); #else string command = "rd /s /q "; // Path may include space. command += """ + pathToSave + """; system(command.c_str()); #endif // Delete recorded version codes. getAssetsManager()->deleteVersion(); createDownloadedDir(); } 但是,这个?
因此,我转而考虑另一个方案。 2. 纯lua纯 lua 其实是个噱头。这里还是要依赖?lfs(lua file sytem),好在 quick-cocos2d-x 已经包含了这个库。 让我们扩展一下 os 包。 require("lfs") function os.exists(path) return CCFileUtils:sharedFileUtils():isFileExist(path) end function os.mkdir(path) if not os.exists(path) then return lfs.mkdir(path) end return true end function os.rmdir(path) print("os.rmdir:",path) if os.exists(path) then local function _rmdir(path) local iter,dir_obj = lfs.dir(path) while true do local dir = iter(dir_obj) if dir == nil then break end if dir ~= "." and dir ~= ".." then local curDir = path..dir local mode = lfs.attributes(curDir,"mode") if mode == "directory" then _rmdir(curDir.."/") elseif mode == "file" then os.remove(curDir) end end end local succ,des = os.remove(path) if des then print(des) end return succ end _rmdir(path) end return true end 上面的代码在 iOS 模拟器和 Android 真机上测试成功。Windows系统、Mac OSX 以及 iOS 真机还没有测试。我测试后会立即更新。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |