linux平台:使用lua语言遍历某一文件夹下所有文件

如题

你可以参考如下实例代码:function getFile(file_name) 
    local f = assert(io.open(file_name, 'r'))
    local string = f:read("*all")
    f:close()
    return string
end function writeFile(file_name,string)
 local f = assert(io.open(file_name, 'w'))
 f:write(string)
 f:close()
end --从命令行获取参数, 如果有参数则遍历指定目录,没有参数遍历当前目录 if arg[1] ~= nil then
     cmd = "ls "..arg[1]
else
     cmd = "ls" end print("cmd", cmd)
--io.popen 返回的是一个FILE,跟c里面的popen一样 local s = io.popen(cmd)
local fileLists = s:read("*all")
print(fileLists)
while true do --从文件列表里一行一行的获取文件名 _,end_pos, line = string.find(fileLists, "([^\n\r]+.txt)", start_pos)
        if not end_pos then break end --    print ("wld", line) local str = getFile(line)
    --把每一行的末尾 1, 替换为 0, local new =string.gsub(str, "1,\n", "0,\n");
    --替换后的字符串写入到文件。以前的内容会清空     writeFile(line, new)
    start_pos = end_pos + 1 end
温馨提示:答案为网友推荐,仅供参考