Lua中I/O庫用于讀取和處理文件。有兩種類型的文件操作,在Lua即隱含文件的描述符和明確的文件描述符。
對(duì)于下面的例子中,我們將使用一個(gè)示例文件test.lua,如下圖所示。
復(fù)制代碼 代碼如下:
-- sample test.lua
-- sample2 test.lua
一個(gè)簡(jiǎn)單的文件打開操作使用下面的語句。
復(fù)制代碼 代碼如下:
file = io.open (filename [, mode])
各種文件模式列示于下表中。
![](http://img.jbzj.com/file_images/article/201505/2015529104548726.jpg?2015429104630)
隱文件描述符
隱文件描述符使用標(biāo)準(zhǔn)輸入/輸出模式,或使用單輸入單輸出文件。使用隱式文件的描述符的一個(gè)示例如下所示。
復(fù)制代碼 代碼如下:
-- Opens a file in read
file = io.open("test.lua", "r")
-- sets the default input file as test.lua
io.input(file)
-- prints the first line of the file
print(io.read())
-- closes the open file
io.close(file)
-- Opens a file in append mode
file = io.open("test.lua", "a")
-- sets the default output file as test.lua
io.output(file)
-- appends a word test to the last line of the file
io.write("-- End of the test.lua file")
-- closes the open file
io.close(file)
當(dāng)運(yùn)行程序,會(huì)得到test.lua文件的第一行輸出。這里例子中得到了下面的輸出。
復(fù)制代碼 代碼如下:
-- Sample test.lua
這是聲明 test.lua 文件的第一行?!?- End of the test.lua file” 將被追加到test.lua代碼的最后一行
在上面的例子中可以看到隱描述與使用文件系統(tǒng)io.“×”方法是如何工作的。上面的例子使用io.read()沒有可選參數(shù)。可選參數(shù)可以是以下任意一個(gè)。
![](http://img.jbzj.com/file_images/article/201505/2015529104828382.jpg?2015429104838)
其他常見的IO方法包括:
- io.tmpfile(): 返回讀寫臨時(shí)文件,一旦程序退出,文件將被刪除。
- io.type(file): 返回文件,關(guān)閉文件或零根據(jù)所輸入的文件。
- io.flush(): 清除默認(rèn)輸出緩沖器。
- io.lines(optional file name): 提供了一個(gè)通用的循環(huán)迭代器遍歷文件并關(guān)閉在最后的情況下提供文件名和默認(rèn)文件的文件被使用,在循環(huán)的末尾沒有關(guān)閉。
明確的文件描述符
我們經(jīng)常使用明確的文件描述符,使我們能夠在同一時(shí)間處理多個(gè)文件。這些功能都相當(dāng)相似的隱式文件描述符。在這里,我們使用的文件:函數(shù)名,而不是io.function_name。同樣地隱文件描述符例的文件版本,以下示例如下所示。
復(fù)制代碼 代碼如下:
-- Opens a file in read mode
file = io.open("test.lua", "r")
-- prints the first line of the file
print(file:read())
-- closes the opened file
file:close()
-- Opens a file in append mode
file = io.open("test.lua", "a")
-- appends a word test to the last line of the file
file:write("--test")
-- closes the open file
file:close()
當(dāng)運(yùn)行程序,會(huì)得到的隱含描述的例子是類似的輸出。
復(fù)制代碼 代碼如下:
-- Sample test.lua
文件打開和參數(shù)進(jìn)行讀取外部描述的所有的模式是一樣的隱含文件的描述符。
其他常見的文件的方法包括:
- file:seek(optional whence, optional offset): 參數(shù)"set", "cur" 或 "end"。設(shè)置新的文件指針從文件的開始更新的文件的位置。偏移量是零基礎(chǔ)的這個(gè)功能。從如果第一個(gè)參數(shù)是“set”該文件的開始時(shí)所測(cè)的偏移量;從如果它是“cur” 文件中的當(dāng)前位置;或從該文件的結(jié)束,如果是“end”。默認(rèn)參數(shù)值是“cur”和0,因此當(dāng)前的文件位置可以通過調(diào)用不帶參數(shù)這個(gè)函數(shù)來獲得。
- file:flush(): 清除默認(rèn)輸出緩沖器。
- io.lines(optional file name): 提供了一個(gè)通用的循環(huán)迭代器遍歷文件并關(guān)閉在最后的情況下提供文件名和默認(rèn)文件的文件被使用,在循環(huán)的末尾沒有關(guān)閉。
一個(gè)例子,以使用尋求方法如下所示。offsets從25個(gè)位置的光標(biāo)之前的文件的末尾。從文件的讀出功能的打印剩余 seek 位置。
復(fù)制代碼 代碼如下:
-- Opens a file in read
file = io.open("test.lua", "r")
file:seek("end",-25)
print(file:read("*a"))
-- closes the opened file
file:close()
會(huì)得到類似下面的一些輸出。
復(fù)制代碼 代碼如下:
sample2 test.lua
--test
可以使用各種不同的模式和參數(shù)了解 Lua文件操作能力。
您可能感興趣的文章:- Lua中遍歷文件操作代碼實(shí)例
- lua文件操作詳解