Lua io文件操作相关

学习目标:

Lua I/O 库用于读取和处理文件。分为简单模式(和C一样)、完全模式。

简单模式(simple model)拥有一个当前输入文件和一个当前输出文件,并且提供针对这些文件相关的操作。
完全模式(complete model) 使用外部的文件句柄来实现。它以一种面对对象的形式,将所有的文件操作定义为文件句柄的方法
简单模式在做一些简单的文件操作时较为合适。但是在进行一些高级的文件操作的时候,简单模式就显得力不从心。例如同时读取多个文件这样的操作,使用完全模式则较为合适。

-- io 文件操作

--简单模式
--r 只读方式打开
print("YC ————————————> 01")
--~ file = io.open("C:\Users\Administrator\Desktop\Test\StudentLua\data1.txt","r")
file = io.open("C:\\Users\\Administrator\\Desktop\\Test\\StudentLua\\data1.txt","r")
print("A",file)
io.input(file)
s = io.read()
print(s)
s = io.read()
print(s)
s = io.read()
print(s)
s = io.read()
print(s)
io.close(file)

print("\nYC ————————————> 02")
file = io.open("C:\\Users\\Administrator\\Desktop\\Test\\StudentLua\\data1.txt","a")
io.output(file)
print("A",file)
s = io.write("\n香草萌萌茶")
print(s)
io.close(file)


print("\nYC ————————————> 03")
--r 只读方式打开
file = io.open("C:\\Users\\Administrator\\Desktop\\Test\\StudentLua\\data1.txt","r")
--读取文件
io.input(file)
print(io.read(3))     --number  返回一个指定字符个数的字符串
print(io.read("*l"))  --读取一行
print(io.read("*n"))  --读取数字
print(io.read("*a"))  --读取所有内容
io.close(file)



--完全模式
--读取
print("\nYC ————————————> 04")
file = io.open("C:\\Users\\Administrator\\Desktop\\Test\\StudentLua\\data1.txt","r")
s = file:read("*a")
print(s)
files = io.open("C:\\Users\\Administrator\\Desktop\\Test\\StudentLua\\data1.txt","r")
s = files:read("*a")
print(s)
file:close()
files:close()


--写入
print("\nYC ————————————> 05")
file = io.open("C:\\Users\\Administrator\\Desktop\\Test\\StudentLua\\data1.txt","a")
s = file:write("\n123")
print(s)
files = io.open("C:\\Users\\Administrator\\Desktop\\Test\\StudentLua\\data1.txt","a")
s = files:write("\n456")
print(s)
file:close()
files:close()


--同时读取与写入
print("\nYC ————————————> 06")
file = io.open("C:\\Users\\Administrator\\Desktop\\Test\\StudentLua\\data1.txt","r")
s = file:read("*a")
print(s)
files = io.open("C:\\Users\\Administrator\\Desktop\\Test\\StudentLua\\data1.txt","a")
s = files:write("\n789")
print(s)
file:close()
files:close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值