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

Lua 獲取文件長度與存在性檢查:兩個實用工具函數

     編輯:更多程式設計知識

文件操作高頻需求:獲取大小、檢查存在。本文提供兩個獨立、可復用的 Lua 函數,基於標準庫 io 實現,無外部依賴。

1. 獲取文件長度 (字節數)


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" 確保跨平台字節數準確。

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.lua") then
    dofile("config.lua")
end

3. 組合使用:安全讀取文件全部內容


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) 統一調用。

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