首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Lua 判斷文件/目錄是否存在:io.open 與封裝函數

     編輯:更多程式設計知識

Lua 標準庫無專用文件存在性檢查函數,**通用做法:嘗試以只讀模式打開,成功即存在**。本文給出 io.open 直接用法與可復用封裝函數。

1. 直接用 io.open


local file, err = io.open("path/to/file", "r")
if file then
    file:close()
    print("文件存在")
else
    print("文件不存在: ", err)  -- "No such file or directory"
end
  • "r":只讀模式,文件必須存在。
  • "rb":二進制只讀,跨平台更安全 (Windows 避免換行符轉換)。
  • 返還值:file (userdata 文件句柄) 或 nil + 錯誤信息字符串。

2. 封裝通用函數


function file_exists(path)
    local file = io.open(path, "rb")
    if file then file:close() end
    return file ~= nil
end

-- 用法
if file_exists("config.ini") then
    load_config()
else
    create_default_config()
end

3. 判斷目錄是否存在

Lua 無原生目錄檢查,**技巧:嘗試打開目錄路徑**,某些系統允許打開目錄獲取句柄,但行為不一致。跨平台建議:

  • **os.execute + Shell 命令** (依賴平台):os.execute('test -d "' .. path .. '"') == 0 (Linux/macOS),os.execute('if exist "' .. path .. '\\nul" exit 0') (Windows)。
  • **lfs (LuaFileSystem) 庫** (推薦):lfs.attributes(path, "mode") == "directory"。
  • **io.popen('dir "'..path..'"')** 讀取輸出判斷 (Windows)。

總結

文件存在性:io.open(path, "rb") 封裝為 file_exists() 最簡可靠。 目錄檢查建議引入 lfs 庫或平台相關 Shell 命令。避免自造輪子,標準庫+成熟庫組合最穩健。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved