学习目标:
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()