萬盛學電腦網

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

Lua 取得檔案大小與存在性檢查:兩個實用工具函式

取得檔案大小(位元組)

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) 還原。
  • 大檔案(>2GB)在 32 位 Lua 可能溢位,建議用 Lua 5.3+ (64 位整數) 或 lfs.attributes。

結語

兩個 <5 行函式,解決 90% 檔案屬性查詢需求。記住 rb + seek("end") 組合,是 Lua 檔案大小獲取的標準姿勢。

copyright © 萬盛學電腦網 all rights reserved