大粨兔奶糖

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

lua IO (file)

概述

lua IO 库用于读写文件, 分为简单模式和完全模式

简单模式: 通过文件输入流, 输出流完成文件操作

完全模式: 使用文件句柄完成文件操作, 以面向对象的操作方式, 将操作定义为文件句柄的方法

简单模式

操作步骤

  • 获取文件句柄
  • 设置流
  • 操作文件
  • 关闭文件

读取操作示例

f = io.open("test.lua", "r")
io.input(f)
print(io.read())
io.close(f)

写入操作示例

f = io.open("test.lua", "a")
io.output(f)
io.write("hello world")
io.close(f)

获取文件句柄的模式

模式 描述 文件是否必须存在
r 只读
w 只写 否, 若不存在, 则新建
a 追加 否, 若不存在, 则新建
r+ 读写
w+ 读写 否, 若不存在, 则新建
a+ 追加, 读写 否, 若不存在, 则新建
b 二进制
+ 可读写

常用方法

函数 描述 备注
io.read 从 io 流中读取数据 io.read("param"), param 可以是 "* n", "* a", "* |", "number"
io.tmpfile 创建临时文件, 程序结束时自动删除 io.tmpfile()
io.type 检查文件句柄是否可用 io.type(file)
io.flush 将 io 流中的数据刷新到文件 io.flush()
io.lines 每次调用会获取文件中的一行内容, 当到文件尾时, 将返回 nil io.lines(file)

io.read 方法参数说明

参数 描述
*n 读取一个数字并返回
*a 从当前位置读取整个文件
*| 读取下一行
number 数字, 读取指定字符个数的字符串

完全模式

操作步骤

  • 获取文件句柄
  • 调用文件对象读写方法
  • 关闭文件

读取操作示例

f = io.open("test.lua", "r")
print(f:read(5))
f:close()

写入操作示例

f = io.open("test.lua", "a")
f:write("liaoliao")
f:close()

常用方法

方法 描述 备注
file:seek 设置文件指针 file:seek(optional whence, optional offset)
file:flush 将缓冲区数据写入文件 file:flush()

file:seek 方法 whence 参数说明

参数 描述
set 文件头
cur 当前位置
end 文件尾
offset 偏移量, 默认为 0
posted on 2017-04-21 09:51  大粨兔奶糖  阅读(387)  评论(0编辑  收藏  举报