local function file_size(path)
local f = assert(io.open(path, "rb"))
local size = f:seek("end") -- 移至末尾,回傳當前位置 = 檔案大小
f:close()
return size
end
-- 用法
print(file_size("data.bin")) -- 1048576
local function file_exists(path)
local f = io.open(path, "rb")
if f then f:close() end
return f ~= nil
end
local path = "upload.zip"
if file_exists(path) then
print(string.format("檔案存在,大小: %.2f MB", file_size(path) / 1024 / 1024))
else
print("檔案不存在")
end
rb 二進位模式:跨平台一致、避免 \r\n 轉換影響位置計算。f:seek("end") 回傳位元組偏移,即檔案大小;若需保留當前位置,先 local cur = f:seek() 再 f:seek("set", cur) 還原。lfs.attributes。兩個 <5 行函式,解決 90% 檔案屬性查詢需求。記住 rb + seek("end") 組合,是 Lua 檔案大小獲取的標準姿勢。