lua文件处理有两种模式:
简单模式:拥有一个当前输入文件和一个当前输出文件,并且提供针对这些文件相关的操作,适用于简单的文件操作
完全模式:使用外部的文件句柄来实现。它以一种面对对象的形式,将所有的文件操作定义为文件句柄的方法,适用于高级文件操作,例如同时读取多个文件
简单模式
file = io.open (filename [, mode])
mode | 作用 |
r | 读,文件不存在则报错 |
w | 写,若文件存在则覆盖重写,若文件不存在则新建 |
a | 写,若文件不存在,则新建;如果文件存在,则在文件尾追加要写的内容 |
r+ | 读写,文件不存在则报错 |
w+ | 读写,若文件存在则覆盖重写,若文件不存在则新建 |
a+ | 读写,若文件不存在,则新建;如果文件存在,则在文件尾追加要写的内容 |
b | 以二进制模式打开文件 |
file=io.open("/test.txt","r")
io.input(file)-- 设置默认输入文件
print(io.read())
io.close()
file=io.open("/test.txt","a")
io.output(file)-- 设置默认输出文件
io.write("last row!")
io.close()
test.txt原始内容为:
hello
world
lua
输出为:
hello
写入之后的文件内容为:
hello
world
lua
last row!
io.read()参数
参数 | 作用 |
“*n” | 读取一个数字并返回它 |
“*a” | 从当前位置读取整个文件 |
“*l”(默认) | 读取下一行,在文件尾 处返回 nil |
number | 返回一个指定字符个数的字符串,在 EOF 时返回 nil |
io的其他用法
方法 | 作用 |
io.tmpfile() | 返回一个临时文件句柄,该文件以更新模式打开,程序结束时自动删除 |
io.type(file) | 检测obj是否一个可用的文件句柄 |
io.flush() | 向文件写入缓冲中的所有数据 |
io.lines(optional file name) | 返回一个迭代函数,每次调用将获得文件中的一行内容,当到文件尾时,将返回nil,但不关闭文件 |
输出文件全部内容:
for lin in io.lines("test.txt") do
print(lin)
end
--[[
hello
world
lua
last row!
]]--
file=io.open("test.txt","r")
print(file:read("*a"))
io.close()
--[[
hello
world
lua
last row!
]]--
完全模式
如果需要在同一时间处理多个文件,需要使用 file:function_name 来代替 io.function_name 方法
file=io.open("test.txt","r")
print(file:read())
io.close()
file=io.open("test.txt","a")
file:write("last row!")
io.close()
运行结果和上面是一样的
file:seek(whence,offset)
设置和获取当前文件位置,成功则返回最终的文件位置(按字节),失败则返回nil加错误信息。参数 whence 值可以是:
“set”: 从文件头开始
“cur”: 从当前位置开始[默认]
“end”: 从文件尾开始
offset:默认为0
文件中还是这些内容:
hello
world
lua
last row!
file=io.open("test.txt","r")
file:seek("set",2)
print(file:read("*a"))
file:close()
--[[
llo
world
lua
last row!
]]--