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

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

你可以参考如下实例代码: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

如果在Windows下(……Linux行不行不知道)

obj=io.popen("cd") --如果不在交互模式下,前面可以添加local

path=obj:read("*all"):sub(1,-2)--path存放当前路径

obj:close() --关掉句柄

上述原理是利用Windows的cd命令返回工作目录;至于sub(1,-2)是为了去掉换行符

当然如果你有lua socks或者你有lfs(注意匹配你的Lua版本),你可以使用lfs(Lua File System)

require("lfs")

path=lfs.currentdir()

这个则是Lua文件系统库中的函数。

……就是这样


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/6072188.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-13
下一篇 2023-03-13

发表评论

登录后才能评论

评论列表(0条)

保存