Lua中的文件I/O操作教程(lua文件写入)全程干货

随心笔谈12个月前发布 admin
89 0



 Lua中I/O库用于读取和处理文件。有两种类型的文件操作,在Lua即隐含文件的描述符和明确的文件描述符。

对于下面的例子中,我们将使用一个示例文件test.lua,如下图所示。

复制代码 代码如下:

— sample test.lua

— sample2 test.lua

一个简单的文件打开操作使用下面的语句。

复制代码 代码如下:
file=io.open (filename [, mode])

各种文件模式列示于下表中。

2015529104548726.jpg (625×282)

 隐文件描述符

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

复制代码 代码如下:

— 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()没有可选参数。可选参数可以是以下任意一个。

2015529104828382.jpg (629×218)

 其他常见的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文件操作能力。

您可能感兴趣的文章:Lua中遍历文件操作代码实例lua文件操作详解

© 版权声明

相关文章