【Lua】使用lfs遍历文件目录

到公司了,开始学习 Lua,看的《Programming In Lua》,大致看了五章,公司培训出的题。


尝试用Lua脚本写一个文件系统访问的代码,要求遍历目录,输出文件名、文件类型(文件或是目录)以及文件的后缀名


果然小白,搞了近3个小时。一个很重要的工具是LFS,即LuaFileSystem,帮助我们访问文件系统。

主要参考了:lua lfs库的使用,递归获取子文件路径 ,lua 获取文件名和扩展名LuaFileSystem


--lua

require "lfs"

--get filename
function getFileName(str)
    local idx = str:match(".+()%.%w+$")
    if(idx) then
        return str:sub(1, idx-1)
    else
        return str
    end
end

--get file postfix
function getExtension(str)
    return str:match(".+%.(%w+)$")
end


function fun(rootpath)
    for entry in lfs.dir(rootpath) do
        if entry ~= '.' and entry ~= '..' then
            local path = rootpath .. '\\' .. entry
            local attr = lfs.attributes(path)
            --print(path)
			local filename = getFileName(entry)

			if attr.mode ~= 'directory' then
				local postfix = getExtension(entry)
				print(filename .. '\t' .. attr.mode .. '\t' .. postfix)
			else
				print(filename .. '\t' .. attr.mode)
				fun(path)
			end
        end
    end
end


fun("E:\\software")





  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值