在使用 quick-cocos2d-x 做項目熱更新的時候,我需要建立臨時文件夾以保存下載的更新包。在更新完成后,我需要刪除這些臨時文件和文件夾。
cocos2d-x 和 quick-cocos2d-x 都沒有提供刪除文件夾功能。我做了如下2個嘗試:
1. 使用C++
在 cocos2d-x 2.x 中的 AssetsManager 包中提供了一個 CreateDirectory 方法。這個方法可以跨平臺支持創(chuàng)建文件夾。在實際項目中運行沒有問題。
return true;
#else
BOOL ret = CreateDirectoryA(path, NULL);
if (!ret ERROR_ALREADY_EXISTS != GetLastError())
{
return false;
}
return true;
#endif
}
// 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();
}
The iOS Simulator libSystem was initialized out of order. This is most often caused by running host executables or inserting host dylibs. In the future, this will cause an abort.
因此,我轉(zhuǎn)而考慮另一個方案。
2. 純lua
純 lua 其實是個噱頭。這里還是要依賴 lfs(lua file sytem),好在 quick-cocos2d-x 已經(jīng)包含了這個庫。
lfs.rmdir 命令 和 os.remove 命令一樣,只能刪除空文件夾。因此實現(xiàn)類似 rm -rf 的功能, 必須要遞歸刪除文件夾中所有的文件和子文件夾。
讓我們擴(kuò)展一下 os 包。
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
標(biāo)簽:德宏 儋州 宣城 金昌 臺灣 天門 天門 濰坊
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Lua中實現(xiàn)遞歸刪除一個文件夾》,本文關(guān)鍵詞 Lua,中,實現(xiàn),遞歸,刪除,一個,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。