Lua - 檔案 I/O



I/O 庫用於在 Lua 中讀取和操作檔案。Lua 中有兩種檔案操作,即隱式檔案描述符和顯式檔案描述符。

對於以下示例,我們將使用如下所示的示例檔案 test.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+"

啟用讀模式的追加模式,開啟現有檔案或建立新檔案。

隱式檔案描述符

隱式檔案描述符使用標準輸入/輸出模式或使用單個輸入和單個輸出檔案。使用隱式檔案描述符的示例如下所示。

main.lua

-- 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

數字

讀取函式中指定的位元組數。

其他常見的 I/O 方法包括:

  • io.tmpfile() - 返回一個臨時檔案,用於讀取和寫入,程式退出後將被刪除。

  • io.type(file) - 根據輸入檔案返回檔案、已關閉檔案或 nil。

  • io.flush() - 清除預設輸出緩衝區。

  • io.lines(可選檔名) - 提供一個通用的 for 迴圈迭代器,迴圈遍歷檔案並在最後關閉檔案,如果提供了檔名或使用了預設檔案並且在迴圈結束時未關閉。

顯式檔案描述符

我們經常使用顯式檔案描述符,它允許我們同時操作多個檔案。這些函式與隱式檔案描述符非常相似。在這裡,我們使用 file:function_name 代替 io.function_name。以下示例顯示了與相同隱式檔案描述符示例相同的檔案版本。

main.lua

-- 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(可選的 whence,可選的 offset) - Whence 引數是 "set"、"cur" 或 "end"。使用從檔案開頭更新的檔案位置設定新的檔案指標。此函式中的偏移量為零基。如果第一個引數為 "set",則偏移量從檔案開頭測量;如果為 "cur",則從檔案中的當前位置測量;如果為 "end",則從檔案末尾測量。預設引數值為 "cur" 和 0,因此可以透過不帶引數地呼叫此函式來獲取當前檔案位置。

  • file:flush() - 清除預設輸出緩衝區。

  • io.lines(可選檔名) - 提供一個通用的 for 迴圈迭代器,迴圈遍歷檔案並在最後關閉檔案,如果提供了檔名或使用了預設檔案並且在迴圈結束時未關閉。

使用 seek 方法的示例如下所示。它將游標從檔案末尾之前的 25 個位置偏移。read 函式列印從 seek 位置開始的檔案的其餘部分。

main.lua

-- Opens a file in read
file = io.open("test.lua", "r")

file:seek("end",-5)
print(file:read("*a"))

-- closes the opened file
file:close()

輸出

您將獲得一些類似於以下內容的輸出。

--test

您可以嘗試所有不同的模式和引數,以瞭解 Lua 檔案操作的全部功能。

廣告

© . All rights reserved.