require("lfs")
LuaFileSystem,简称lfs
是一个用于Lua进行文件访问的库,支持Lua5.1和Lua5.2,且跨平台。Lua5.1+版本已经内置了,具体位置Lua5.1\clibs\lfs.dll
,无需配置直接引入即可使用。
luarocks
luarocks
是一个用于安装Lua库的软件,是独立于Lua的,可在线安装一些Lua库,如lfs
。
接口
lfs.chdir(path)
lfs.chdir(path)
- 将当前目录修改为给定的路径
lfs.currentdir()
lfs.currentdir()
- 获取当前目录
lfs.dir(path)
lfs.dir(path)
- 遍历目录下所有入口,每次迭代返回值都作为入口名称的字符串。
lfs.lock(fileHandler, mode[,start[,length]]
lfs.handler(fileHandler, mode[, start[, length]]
- 锁定文件或文件的部分内容
lfs.mkdir(dirname)
lfs.mkdir(dirname)
- 创建目录
lfs.rmdir(dirname)
lfs.rmdir(dirname)
- 移除已存在的目录
lfs.setmode(file,mode)
lfs.setmode(file, mode)
- 设置文件写入模式,mode字符串可以是binary或text。
lfs.symlinkattributes(filepath[, aname])
lfs.symlinkattributes(filepath[, aname])
- 比 lfs.attributes多了 the link itself(not the file it refers to)信息,其他均一样。
lfs.touch(filepath [, atime [, mtime]])
lfs.touch(filepath [, atime [, mtime]])
-- 设置上次使用和修改文件的时间值
lfs.unlock(fileHandler[, start[, length]]
lfs.unlock(fileHandler[, start[, length]])
- 解锁文件或解锁文件的部分内容
lfs.attributes(filepath[, aname])
lfs.attributes(filepath[, aname])
- 获取路径指定属性
返回filepath文件路径属性的table,若filepath是nil则会出错并打印错误信息。
路径属性
- dev
- info UNIX下表示inode数目,windows下无意义。
- mode 字符串,关联的保护模式,值可为file、directory、link、socket、named pipe、char device、block device、other。
- nlink 文件上的硬链接数
- uid UNIX中目录的user-id,Windows为0。
- gid UNIX中用户的组ID,Windows为0。
- rdev Linux下表示设备类型,Windows下和dev值相同。
- access 最近一次访问时间
- modification 最近一次修改时间
- change 最近一次文件状态修改时间
- size 文件大小,以字节为单位。
- blocks UNIX中分配给文件的块大小
- blksize UNIX中I/O的块大小
示例
require 'lfs'
-- 使用LFS递归遍历目录
function findInDir(path, find, table, dir)
for filename in lfs.dir(path) do
if filename~="." and filename~=".." then
local filepath = path..''..filename
if string.find(filepath, find)!=nil then
table.insert(table, filepath)
end
local fileattr = lfs.attributes(filepath)
assert(type(fileattr)=='table')
if fileattr.mode=='directory' and dir then
findInDir(filepath, find, table , dir)
else
for name,value in paires(fileattr) do
print(name,value)
end
end
end
end
end