Lua中的檔案I/O操作教程
這篇文章主要介紹了Lua中的檔案I/O操作教程,是Lua入門學習中的基礎知識,需要的朋友可以參考下
Lua中I/O庫用於讀取和處理檔案。有兩種類型的檔案操作,在Lua即隱含檔案的描述符和明確的檔案描述符。
對於下面的例子中,我們將使用一個樣本檔案test.lua,如所示。
代碼如下:
-- sample test.lua
-- sample2 test.lua
一個簡單的檔案開啟操作使用下面的語句。
代碼如下:
file = io.open (filename [, mode])
各種檔案模式列示於下表中。
隱檔案描述符
隱檔案描述符使用標準輸入/輸出模式,或使用單輸入單輸出檔案。使用隱式檔案的描述符的一個樣本如下所示。
代碼如下:
-- 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.“×”方法是如何工作的。上面的例子使用io.read()沒有選擇性參數。選擇性參數可以是以下任意一個。
其他常見的IO方法包括:
io.tmpfile(): 返回讀寫臨時檔案,一旦程式退出,檔案將被刪除。
io.type(file): 返迴文件,關閉檔案或零根據所輸入的檔案。
io.flush(): 清除預設輸出緩衝器。
io.lines(optional file 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): 提供了一個通用的迴圈迭代器遍曆檔案並關閉在最後的情況下提供檔案名稱和預設檔案的檔案被使用,在迴圈的末尾沒有關閉。
一個例子,以使用尋求方法如下所示。offsets從25個位置的游標之前的檔案的末尾。從檔案的讀出功能的列印剩餘 seek 位置。
代碼如下:
-- 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檔案操作能力。