文件操作高頻需求:獲取大小、檢查存在。本文提供兩個獨立、可復用的 Lua 函數,基於標準庫 io 實現,無外部依賴。
function length_of_file(filename)
local fh = assert(io.open(filename, "rb")) -- 二進制只讀
local len = assert(fh:seek("end")) -- 移至文件末尾,返回位置即長度
fh:close()
return len
end
-- 用法
local size = length_of_file("data.bin")
print("文件大小: " .. size .. " bytes")
fh:seek("end") 將游標移至文件末尾,返回當前位置 (即文件長度)。assert 保證打開/定位失敗時拋出錯誤,調用方可 pcall 捕獲。"rb" 確保跨平台字節數準確。
function file_exists(path)
local file = io.open(path, "rb")
if file then file:close() end
return file ~= nil
end
-- 用法
if file_exists("config.lua") then
dofile("config.lua")
end
function read_all_file(filename)
if not file_exists(filename) then return nil, "not found" end
local fh = assert(io.open(filename, "rb"))
local content = fh:read("*a") -- 讀取全部
fh:close()
return content
end
**length_of_file 用 seek("end")、file_exists 用 io.open 封裝**,兩函數簡潔、健壯、零依賴,建議收錄至項目通用工具模塊 (utils.file) 統一調用。