萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Lua 判斷檔案/目錄是否存在:io.open 與封裝函式

核心原理:io.open 回傳值

local file, err = io.open(path, "r")
if file then
    file:close()
    print("存在")
else
    print("不存在: " .. err)  -- "No such file or directory"
end
  • 成功:回傳 **檔案控制代碼**、err = nil。
  • 失敗:回傳 nil、err 含錯誤訊息。
  • **同樣適用於目錄**(嘗試開啟目錄會失敗並回傳錯誤)。

通用封裝函式

local function file_exists(path)
    local f = io.open(path, "rb")  -- 二進位模式避免換行轉換
    if f then f:close() end
    return f ~= nil
end

-- 用法
if file_exists("/etc/nginx/nginx.conf") then
    ngx.say("設定檔存在")
end

進階:區分檔案 vs 目錄(需 lfs)

local lfs = require("lfs")

local function path_type(path)
    local attr, err = lfs.attributes(path)
    if not attr then return nil, err end  -- 不存在
    return attr.mode  -- "file" / "directory" / "link" / "socket" ...
end

-- 用法
local t = path_type("/var/log")
if t == "directory" then print("是目錄") end

結語

純 Lua 判斷存在性:**io.open(path, "rb") 即可**。需區分檔案/目錄型別時,引入 lua-filesystem (lfs) 取得 attributes。記得關閉檔案控制代碼,避免洩漏。

copyright © 萬盛學電腦網 all rights reserved