I/O庫提供兩種不同的方式進行文件處理:
io表調用方式
使用io表,io.open將返回指定文件的描述,并且所有的操作將圍繞這個文件描述。io表同樣提供三種預定義的文件描述io.stdin,io.stdout,io.stderr
文件句柄直接調用方式
即使用file:XXX()函數方式進行操作,其中file為io.open()返回的文件句柄。多數I/O函數調用失敗時返回nil加錯誤信息,有些函數成功時返回nil
IO
io.close ([file])
io.flush ()
相當于file:flush(),輸出所有緩沖中的內容到默認輸出文件
io.lines ([filename])
打開指定的文件filename為讀模式并返回一個迭代函數,每次調用將獲得文件中的一行內容,當到文件尾時,將返回nil,并自動關閉文件,若不帶參數時io.lines() => io.input():lines(); 讀取默認輸入設備的內容,但結束時不關閉文件
for line in io.lines("main.lua") do
print(line)
end
io.open (filename [, mode])
mode:
"r": 讀模式 (默認);
"w": 寫模式;
"a": 添加模式;
"r+": 更新模式,所有之前的數據將被保存
"w+": 更新模式,所有之前的數據將被清除
"a+": 添加更新模式,所有之前的數據將被保存,只允許在文件尾進行添加
"b": 某些系統支持二進制方式
io.read (...)
io.type (obj)
檢測obj是否一個可用的文件句柄
返回:
"file":為一個打開的文件句柄
"closed file":為一個已關閉的文件句柄
nil:表示obj不是一個文件句柄
io.write (...)
相當于io.output():write
File
file:close()
當文件句柄被垃圾收集后,文件將自動關閉。句柄將變為一個不可預知的值
file:flush()
向文件寫入緩沖中的所有數據
file:lines()
返回一個迭代函數,每次調用將獲得文件中的一行內容,當到文件尾時,將返回nil,但不關閉文件
for line in file:lines() do body end
file:read(...)
按指定的格式讀取一個文件,按每個格式函數將返回一個字串或數字,如果不能正確讀取將返回nil,若沒有指定格式將指默認按行方式進行讀取
格式:
"n": 讀取一個數字 ("number")
"a": 從當前位置讀取整個文件,若為文件尾,則返回空字串 ("all")
"l": [默認]讀取下一行的內容,若為文件尾,則返回nil ("line")
number: 讀取指定字節數的字符,若為文件尾,則返回nil;如果number為0則返回空字串,若為文件尾,則返回nil;
file:seek(whence)
設置和獲取當前文件位置,成功則返回最終的文件位置(按字節),失敗則返回nil加錯誤信息
參數
whence:
"set": 從文件頭開始
"cur": 從當前位置開始[默認]
"end": 從文件尾開始
offset:默認為0
不帶參數file:seek()則返回當前位置,file:seek("set")則定位到文件頭,file:seek("end")則定位到文件尾并返回文件大小
file:write(...)
按指定的參數格式輸出文件內容,參數必須為字符或數字,若要輸出其它值,則需通過tostring或string.format進行轉換
實例
讀取文件所有內容
function readfile(path)
local file = io.open(path, "r")
if file then
local content = file:read("*a")
io.close(file)
return content
end
return nil
end
寫入內容到文件
function writefile(path, content, mode)
mode = mode or "w+b"
local file = io.open(path, mode)
if file then
if file:write(content) == nil then return false end
io.close(file)
return true
else
return false
end
end
文件大小
-- @return : 文件字節數
function filesize(path)
local size = false
local file = io.open(path, "r")
if file then
local current = file:seek()
size = file:seek("end")
file:seek("set", current)
io.close(file)
end
return size
end
文件是否存在
function fileExists(path)
local file = io.open(path, "r")
if file then
io.close(file)
return true
end
return false
end
您可能感興趣的文章:- Lua中遍歷文件操作代碼實例
- Lua中的文件I/O操作教程