使用 Lua,检查文件是否是一个目录。

如果我有以下代码

local f = io.open("../web/", "r")
print(io.type(f))

-- 输出结果: file

我该如何知道 f 指向的是一个目录?

原文链接 https://stackoverflow.com/questions/2833675

点赞
stackoverflow用户126042
stackoverflow用户126042

ANSI C 并没有规定获取目录信息的方式,因此基本的 Lua 无法提供该信息(因为 Lua 力求 100% 的可移植性)。但是,您可以使用外部库,例如 LuaFileSystem 来识别目录。

Progamming in Lua 甚至明确声明了缺少目录功能:

更复杂的例子是编写一个返回给定目录内容的函数。Lua没有在其标准库中提供此函数,因为 ANSI C 没有这项任务的函数。

该示例继续演示如何自己使用 C 编写 dir 函数。

2010-05-14 11:19:44
stackoverflow用户148870
stackoverflow用户148870

Lua 的默认库没有一种方法来确定这一点。

然而,你可以使用第三方 LuaFileSystem 库来获取更高级的文件系统交互;它也是跨平台的。

LuaFileSystem 提供了 lfs.attributes 函数,可以用来查询文件模式:

require "lfs"
function is_dir(path)
    -- lfs.attributes 会在以 '/' 结尾的文件名上报错
    return path:sub(-1) == "/" or lfs.attributes(path, "mode") == "directory"
end
2010-05-14 11:20:23
stackoverflow用户107090
stackoverflow用户107090

如果你执行

local x,err=f:read(1)

此时 err 的值为 "Is a directory"

2010-05-14 11:52:19
stackoverflow用户136303
stackoverflow用户136303

我在使用的库中找到了这段代码:

function is_dir(path)
    local f = io.open(path, "r")
    local ok, err, code = f:read(1)
    f:close()
    return code == 21
end

我不知道在 Windows 上的表现如何,但在 Linux/BSD/OSX 上它可以正常工作。

2010-07-15 08:59:25
stackoverflow用户1787346
stackoverflow用户1787346
function fs.isDir ( file )
    if file == nil then return true end
    if fs.exists(file) then
        os.execute("dir \""..userPath..file.."\" >> "..userPath.."\\Temp\\$temp")
        file = io.open(userPath.."\\Temp\\$temp","r")
        result = false
        for line in file:lines() do
            if string.find(line, "<DIR>") ~= nil then
                result = true
                break
            end
        end
        file:close()
        fs.delete("\\Temp\\$temp")
        if not (result == true or result == false) then
            return "Error"
        else
            return result
        end
    else
        return false
    end
end

这是我从之前发现的一个库中提取的一些代码。

2012-10-31 03:07:34
stackoverflow用户15690
stackoverflow用户15690

这首先检查路径是否可读(空文件也为nil),然后又额外检查大小是否为0。

function is_dir(path)
    f = io.open(path)
    return not f:read(0) and f:seek("end") ~= 0
end
2015-04-15 23:56:53
stackoverflow用户6556580
stackoverflow用户6556580

至少对于 UNIX 操作系统:

如果 os.execute("cd '" .. f .. "'") 因其可执行程序而成功,
那么打印 "是一个文件夹",
否则打印 "不是一个文件夹"

:)

2016-07-13 20:51:07
stackoverflow用户919632
stackoverflow用户919632

由于问题没有指定可移植性的需求,在 Linux/Unix 系统上您可以使用 file 命令:

function file(path)
  local p = io.popen(('file %q'):format(path))
  if p then
    local out = p:read():gsub('^[^:]-:%s*(%w+).*','%1')
    p:close()
    return out
  end
end

if file('/') == 'directory' then
  -- 做某些事情
end

已经测试并在 Lua 5.1 到 5.4 上工作。

2022-08-17 15:52:28