I/O庫提供兩種不同的方式進(jìn)行文件處理:
io表調(diào)用方式
使用io表,io.open將返回指定文件的描述,并且所有的操作將圍繞這個(gè)文件描述。io表同樣提供三種預(yù)定義的文件描述io.stdin,io.stdout,io.stderr
文件句柄直接調(diào)用方式
即使用file:XXX()函數(shù)方式進(jìn)行操作,其中file為io.open()返回的文件句柄。多數(shù)I/O函數(shù)調(diào)用失敗時(shí)返回nil加錯(cuò)誤信息,有些函數(shù)成功時(shí)返回nil
IO
io.close ([file])
io.flush ()
相當(dāng)于file:flush(),輸出所有緩沖中的內(nèi)容到默認(rèn)輸出文件
io.lines ([filename])
打開指定的文件filename為讀模式并返回一個(gè)迭代函數(shù),每次調(diào)用將獲得文件中的一行內(nèi)容,當(dāng)?shù)轿募矔r(shí),將返回nil,并自動(dòng)關(guān)閉文件,若不帶參數(shù)時(shí)io.lines() => io.input():lines(); 讀取默認(rèn)輸入設(shè)備的內(nèi)容,但結(jié)束時(shí)不關(guān)閉文件
for line in io.lines("main.lua") do
print(line)
end
io.open (filename [, mode])
mode:
"r": 讀模式 (默認(rèn));
"w": 寫模式;
"a": 添加模式;
"r+": 更新模式,所有之前的數(shù)據(jù)將被保存
"w+": 更新模式,所有之前的數(shù)據(jù)將被清除
"a+": 添加更新模式,所有之前的數(shù)據(jù)將被保存,只允許在文件尾進(jìn)行添加
"b": 某些系統(tǒng)支持二進(jìn)制方式
io.read (...)
io.type (obj)
檢測obj是否一個(gè)可用的文件句柄
返回:
"file":為一個(gè)打開的文件句柄
"closed file":為一個(gè)已關(guān)閉的文件句柄
nil:表示obj不是一個(gè)文件句柄
io.write (...)
相當(dāng)于io.output():write
File
file:close()
當(dāng)文件句柄被垃圾收集后,文件將自動(dòng)關(guān)閉。句柄將變?yōu)橐粋€(gè)不可預(yù)知的值
file:flush()
向文件寫入緩沖中的所有數(shù)據(jù)
file:lines()
返回一個(gè)迭代函數(shù),每次調(diào)用將獲得文件中的一行內(nèi)容,當(dāng)?shù)轿募矔r(shí),將返回nil,但不關(guān)閉文件
for line in file:lines() do body end
file:read(...)
按指定的格式讀取一個(gè)文件,按每個(gè)格式函數(shù)將返回一個(gè)字串或數(shù)字,如果不能正確讀取將返回nil,若沒有指定格式將指默認(rèn)按行方式進(jìn)行讀取
格式:
"n": 讀取一個(gè)數(shù)字 ("number")
"a": 從當(dāng)前位置讀取整個(gè)文件,若為文件尾,則返回空字串 ("all")
"l": [默認(rèn)]讀取下一行的內(nèi)容,若為文件尾,則返回nil ("line")
number: 讀取指定字節(jié)數(shù)的字符,若為文件尾,則返回nil;如果number為0則返回空字串,若為文件尾,則返回nil;
file:seek(whence)
設(shè)置和獲取當(dāng)前文件位置,成功則返回最終的文件位置(按字節(jié)),失敗則返回nil加錯(cuò)誤信息
參數(shù)
whence:
"set": 從文件頭開始
"cur": 從當(dāng)前位置開始[默認(rèn)]
"end": 從文件尾開始
offset:默認(rèn)為0
不帶參數(shù)file:seek()則返回當(dāng)前位置,file:seek("set")則定位到文件頭,file:seek("end")則定位到文件尾并返回文件大小
file:write(...)
按指定的參數(shù)格式輸出文件內(nèi)容,參數(shù)必須為字符或數(shù)字,若要輸出其它值,則需通過tostring或string.format進(jìn)行轉(zhuǎn)換
實(shí)例
讀取文件所有內(nèi)容
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
寫入內(nèi)容到文件
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 : 文件字節(jié)數(shù)
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中遍歷文件操作代碼實(shí)例
- Lua中的文件I/O操作教程