Lua 基础教程(十七)文件IO

140 阅读4分钟

Lua 基础教程(十七)文件IO

husdon 译 原文

在Lua中 ,I/O库用于读取和操作文件。Lua中有两种文件操作,即隐式文件描述符和显式文件描述符。

下面是示例文件test.lua内容。后续文件IO示例会使用该文件:

-- sample test.lua
-- sample2 test.lua

一个简单的文件打开操作如下:

file = io.open (filename [, mode])

下表列出了各种不同的文件模式。

序号模式描述
1"r"只读模式,是打开现有文件的默认模式。
2"w"写入模式,覆盖现有文件或创建新文件。
3"a"追加模式,打开现有文件或创建新文件以进行追加。
4"r+"读写模式,用于现有文件。
5"w+"如果文件存在,则删除所有现有数据,或者创建具有读写权限的新文件。
6"a+"追加模式,并启用读模式,打开现有文件或创建新文件。

隐式文件描述符

隐式文件描述符使用标准输入/输出模式或使用单个输入和单个输出文件。使用隐式文件描述符的示例如下所示:

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

此外,“--End of the test.lua file ”行将附加到test.lua文件的最后一行。

隐式描述符使用io.”xxx“方法与文件系统一起工作。上述示例中,使用的是io.read()方法,没有可选参数。可选参数可以是以下任何一项:

序号模式描述
1"*n"从当前文件位置读取并返回文件位置处存在的数字,如果不存在则返回 nil。
2"*a"返回从当前文件位置开始的文件的所有内容。
3"*l"从当前文件位置读取一行,并将文件位置移动到下一行。
4number读取函数中指定的字节数。

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

序号方法描述
1io.tmpfile()返回一个临时文件,用于读取和写入,在程序退出时将被删除。
2io.type(file)根据输入文件返回文件、关闭的文件或nil。
3io.flush()清除默认的输出缓冲区。
4io.lines(可选的文件名)提供一个通用的循环迭代器,循环遍历文件并在结束时关闭文件,如果提供了文件名或使用默认文件且在循环结束时未关闭文件。

显式文件描述符

我们经常要用到显式文件描述符,它可以一次操作多个文件。这些操作函数与隐式文件描述符的非常相似。在这里,使用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) − Whence 参数为“set”、“cur”或“end”。 使用从文件开头开始的更新文件位置设置新文件指针。 此外,偏移量是基于零计算的。 如果第一个参数是“set”,则从文件开头开始计算偏移量;如果是“cur”,则从文件中的当前位置计算;如果是“end”,则从文件末尾计算偏移量。 默认参数值为“cur”和0,因此可以通过在没有参数的情况下调用此函数来获得当前文件位置。

  • file:flush() − 清除默认输出缓冲区。

  • io.lines(可选文件名) − 提供一个通用的循环迭代器,遍历文件并在结束后关闭文件。

使用seek方法的示例如下所示。 它将偏移设置为文件结束前的25个位置, 从该位置读取文件其余部分,打印在屏幕上:

-- 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文件操作的全部能力。