I/O庫用於讀取和操作Lua中的檔。 Lua中有兩種檔操作,即隱式檔描述符和顯式檔描述符。
對於以下示例,將使用示例檔 - test.lua,內容如下所示 -
-- sample test.lua
-- sample2 test.lua
檔打開操作使用以下語句 -
file = io.open (filename [, mode])
下表列出了各種檔模式 -
編號 | 模式 | 描述 |
---|---|---|
1 | r |
只讀模式,是打開現有檔的默認模式。 |
2 | w |
寫入啟用模式,覆蓋現有檔或創建新檔。 |
3 | a |
附加模式,用於打開現有檔或創建新檔以進行追加。 |
4 | r+ |
現有檔的讀寫模式。 |
5 | w+ |
如果檔存在或創建具有讀寫許可權的新檔,則刪除所有現有數據。 |
6 | a+ |
啟用了讀取模式的追加模式可打開現有檔或創建新檔。 |
1. 隱式檔描述符
隱式檔描述符使用標準輸入/輸出模式或使用單個輸入和單個輸出檔。 使用隱式檔描述符的示例如下所示。
-- 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)
運行程式時,將獲得test.lua 檔第一行的輸出。執行上面程式,得到以下輸出 -
-- Sample test.lua
這是test.lua 檔中聲明的第一行。 同時也將"-- End of the test.lua file"
這一行附加到test.lua 檔中的最後一行。
在上面的示例中,可以使用io."x"
方法查看隱式描述符如何與檔系統一起使用。 上面的示例使用不帶可選參數的io.read()
方法。可選參數可以是以面中的任何一個。
編號 | 模式 | 描述 |
---|---|---|
1 | *n |
從當前檔位置讀取並返回一個數字(如果存在於檔位置或返回nil )。 |
2 | *a |
從當前檔位置返回檔的所有內容。 |
3 | *l |
從當前檔位置讀取行,並將檔位置移動到下一行。 |
4 | number |
讀取函數中指定的位元組數。 |
其他常見的I/O方法包括,
io.tmpfile()
- 返回一個臨時檔,用於讀取和寫入,當程式退出,將刪除該檔。io.type(file)
- 根據輸入檔返回檔,關閉檔或nil
。io.flush()
- 清除默認輸出緩衝區。io.lines(可選檔案名)
- 提供迴圈迭代器的通用迴圈迭代器,迴圈遍曆檔並最終關閉檔,以防提供檔案名或使用默認檔而不在迴圈結束時關閉。
2. 顯式檔描述符
顯式檔描述符經常使用,它允許一次操作多個檔。 這些函數與隱式檔描述符非常相似。 在這裏,使用file:function_name
,而不是io.function_name
。 下麵顯示了以下相同隱式檔描述符示例的顯式檔描述符版本示例。
-- 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()
運行程式時,將獲得與隱式描述符示例類似的輸出 -
-- Sample test.lua
檔打開的所有模式和用於讀取外部描述符的參數與隱式檔描述符相同。
其他常見的檔方法包括,
file:seek(optional whence, optional offset)
- 參數是set
,cur
或end
。 使用檔開頭的更新檔位置設置新檔指針。 在此函數中,偏移量為零。 如果第一個參數是set
,則從檔的開頭測量偏移量; 從檔中的當前位置開始,如果它是cur
; 或者從檔的末尾開始,則它是end
。 默認參數值為cur
和0
,因此可以通過不帶參數調用此函數來獲取當前檔位置。file:flush()
− 清除默認輸出緩衝區。io.lines(optional file name)
- 提供迴圈迭代器的通用迴圈迭代器,迴圈遍曆檔並最終關閉檔,以防提供檔案名或使用默認檔而不在迴圈結束時關閉。
使用搜索方法的示例如下所示。它將游標從檔結束前的25
個位置偏移。 read
函數從搜索位置列印檔的剩餘部分。
-- 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()
執行上面示例代碼,將獲得類似於以下內容的輸出 -
sample2 test.lua
--test
讀者可自己使用所有的模式和參數來瞭解Lua檔操作的完整功能。