zoukankan      html  css  js  c++  java
  • 【Lua】关于遍历指定路径下所有目录及文件

      关于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(".")

      输出:

  • 相关阅读:
    vue生命周期
    SQL Server 2008教程和Microsoft® SQL Server® 2008 R2 SP2
    min.css----全世界最快的CSS框架
    4分钟网页设计(译文)
    CSS 选择器
    CSS 定位
    [书]WALL·E、龙与地下铁、中国美丽的故事、故事新编、四十自述、书虫、人工智能、大话数据结构
    Underscore.js 初探
    Normalize.css 初识
    什么是 HTML?
  • 原文地址:https://www.cnblogs.com/linxiong945/p/4106053.html
Copyright © 2011-2022 走看看