在Lua中,可以使用io庫來進行文件讀寫操作。以下是一些常用的文件讀寫操作示例:
local file = io.open("file.txt", "r")
if file then
local content = file:read("*a")
print(content)
file:close()
else
print("Error: Unable to open file")
end
local file = io.open("file.txt", "w")
if file then
file:write("Hello, world!")
file:close()
else
print("Error: Unable to open file")
end
local file = io.open("file.txt", "a")
if file then
file:write("\nThis is a new line")
file:close()
else
print("Error: Unable to open file")
end
在進行文件讀寫操作時,需要確保文件的讀寫權限并在操作完成后關閉文件流。