码迷,mamicode.com
首页 > 其他好文 > 详细

lua遍历文件目录

时间:2014-08-23 19:02:01      阅读:630      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   文件   for   div   cti   log   

用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

 

lua遍历文件目录

标签:style   blog   color   io   文件   for   div   cti   log   

原文地址:http://www.cnblogs.com/jiufangding/p/3931585.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!