用lua遍历文件目录,收集特定类型的文件:
1 local LINUX = "linux" 2 local WIN = "win" 3 local platform = WIN 4 5 local need_the_filetype = function(tfiletype, filename) 6 for k, v in pairs(tfiletype) do 7 if (v == ".") or (v == ".*") then 8 return true 9 end 10 11 local from, to = string.find(filename, "%" .. v) 12 while from do 13 local f, t = string.find(filename, "%" .. v, to) 14 if not(f) then 15 break 16 end 17 from, to = f, t 18 end 19 20 if from and (to == string.len(filename)) then 21 return true 22 end 23 end 24 return false 25 end 26 27 local function scan_dir_file(path, tfiletype, tfilename) 28 path = path or "./" 29 tfiletype = tfiletype or {"."} 30 tfilename = tfilename or {} 31 32 local cmd = "ls " .. path 33 if (platform == WIN) then 34 cmd = ‘dir "‘ .. path .. ‘" /b‘ 35 end 36 local popen = io.popen(cmd) 37 if popen then 38 for filename in popen:lines() do 39 if (string.find(filename, "%.")) then 40 if need_the_filetype(tfiletype, filename) then 41 tfilename[#tfilename + 1] = {path = path, name = filename,} 42 end 43 else 44 scan_dir_file(path .. filename .. "/", tfiletype, tfilename) 45 end 46 end 47 end 48 return tfilename 49 end 50 51 --------------------------------- 52 -- interface 53 -- 54 scan = { 55 walk = function(path, tfiletype, tfilename) 56 return scan_dir_file(path, tfiletype, tfilename) 57 end, 58 } 59 60 -------------------------------- 61 -- test 62 -- 63 local t = scan.walk() 64 for k, v in pairs(t) do 65 print(k, v.path, v.name) 66 end
时间: 2024-10-19 10:12:21