Lua - 文件描述符
Lua 提供了 I/O library 来读取和操作文件。在 Lua 中,文件操作使用隐式或显式的 file descriptors 进行。
隐式 File Descriptor 风格
在隐式 file descriptor 风格中,我们对 io table 使用大多数操作,如以下代码片段所示。
示例 - 使用隐式 file descriptors 写入文件
以下示例展示了使用隐式 file descriptors 写入文件的使用方法。
main.lua
-- 要写入的文件
fileName = "example.txt"
-- 以写入模式打开由 fileName 指定的文件
f = io.open(fileName, "w")
-- 设置默认输出文件
io.output(f)
-- 写入内容
io.write("Welcome to example.com", "\n")
io.write("Simply Easy Learning", "\n")
-- 关闭文件
io.close(f)
-- 打印消息
print("Content written successfully.")
输出
当上述代码构建并执行时,会产生以下结果 −
Content written successfully.
解释
这里我们使用 io.open() 方法以写入模式打开文件。
然后使用 io.output() 方法设置默认输出文件。
所有内容使用 io.write() 方法写入。
最后使用 io.close(f) 方法关闭文件句柄。
示例 - 使用隐式 file descriptors 读取文件
以下示例展示了使用隐式 file descriptors 读取文件。
main.lua
-- 要读取的文件 fileName = "example.txt" -- 以读取模式打开由 fileName 指定的文件 f = io.open(fileName, "r") -- 设置默认输入文件 io.input(f) -- 读取模式 mode = "*all" -- 以给定模式读取文件(可选) content = io.read (mode) -- 打印内容 print(content) -- 关闭文件 io.close(f)
输出
Welcome to example.com Simply Easy Learning
解释
这里我们使用 io.open() 方法以读取模式打开文件。
然后使用 io.input() 方法设置默认输入文件。
mode 设置为 *all。
所有内容使用 io.read() 方法读取。
最后使用 io.close(f) 方法关闭文件句柄。
显式 File Descriptor 风格
在显式 file descriptor 风格中,我们对由 io.open() 方法返回的 file handle 使用大多数操作,如以下代码片段所示。
示例 - 使用显式 file descriptors 写入文件
以下代码示例展示了使用显式 file descriptors 写入文件。
main.lua
-- 要写入的文件
fileName = "example.txt"
-- 以写入模式打开由 fileName 指定的文件
f = io.open(fileName, "w")
-- 写入内容
f:write("Welcome to example.com", "\n")
f:write("Simply Easy Learning", "\n")
-- 关闭文件
f:close()
-- 打印消息
print("Content written successfully.")
输出
Content written successfully.
解释
这里我们使用 io.open() 方法以写入模式打开文件。
所有内容使用 f:write() 方法写入。
最后使用 f:close() 方法关闭文件句柄。
示例 - 使用显式 file descriptors 读取文件
以下代码展示了如何使用显式 file descriptors 读取文件。
main.lua
-- 要读取的文件 fileName = "example.txt" -- 以读取模式打开由 fileName 指定的文件 f = io.open(fileName, "r") -- 读取模式 mode = "*all" -- 以给定模式读取文件(可选) content = f:read (mode) -- 打印内容 print(content) -- 关闭文件 f:close()
输出
当上述代码构建并执行时,会产生以下结果 −
Welcome to example.com Simply Easy Learning
解释
这里我们使用 io.open() 方法以读取模式打开文件。
mode 设置为 *all。
所有内容使用 f:read() 方法读取。
最后使用 f:close() 方法关闭文件句柄。