(转)在lua中递归删除一个文件夹

原文地址:http://www.cocoachina.com/bbs/read.php?tid=212786

纯lua
纯 lua 其实是个噱头。这里还是要依赖 lfs(lua file sytem),好在 quick-cocos2d-x 已经包含了这个库。
lfs.rmdir 命令 和 os.remove 命令一样,只能删除空文件夹。因此实现类似 rm -rf 的功能, 必须要递归删除文件夹中所有的文件和子文件夹。
让我们扩展一下 os 包。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
原文地址:https://www.cnblogs.com/wodehao0808/p/9104978.html