關於Lua中如何遍歷指定文件路徑下的所有文件,需要用到Lua的lfs庫。
首先創建一個temp.lua文件,用編輯器打開:
要使用lfs庫,首先需要把lfs庫加載進來
require("lfs")
隨后創建一個函數,用來遍歷指定路徑下的所有文件,這里我們需要用到lfs庫中的lfs.dir()方法和lfs.attributes(f)方法。
lfs.dir(path)
可以返回一個包含path內所有文件的字符串,如果該路徑不是一個目錄,則返回一個錯誤。可以用
for file in lfs.dir(path) do print(file) end
來取得路徑內的各文件名
lfs.attributes(filepath)
返回filepath的各種屬性,包括文件類型、大小、權限等等信息
1 require("lfs") 2 3 function attrdir(path) 4 for file in lfs.dir(path) do 5 if file ~= "." and file ~= ".." then 6 local f = path .. "/" .. file 7 local attr = lfs.attributes(f) 8 print (f) 9 for name, value in pairs(attr) do 10 print (name, value) 11 end 12 end 13 end 14 end 15 16 attrdir("/var/www/tmp/css")
有了這兩個方法,就可以來遍歷指定路徑下的所有文件了:
1 require"lfs" 2 3 function attrdir(path) 4 for file in lfs.dir(path) do 5 if file ~= "." and file ~= ".." then //過濾linux目錄下的"."和".."目錄 6 local f = path.. '/' ..file 7 local attr = lfs.attributes (f) 8 if attr.mode == "directory" then 9 print(f .. " --> " .. attr.mode) 10 attrdir(f) //如果是目錄,則進行遞歸調用 11 else 12 print(f .. " --> " .. attr.mode) 13 end 14 end 15 end 16 end 17 18 attrdir(".")
輸出: