简单IO模式
eg:
如果io.read()参数
"*all"
从当前位置读取整个文件,若为文件尾,则返回空字串
"*line"
"*number"
<num>
读取num个字符到串
–[[test.lua的内容hello world,I is test.luaprint(123)–]] io.input("E:\\workplace\\project\\server\\script\\test\\src\\test.lua") t=io.read("*all") io.write(t, '\n') ——输出整个 test.lua 文件的内容到 stdin–> –hello world,I is test.lua–> print(123)
函数名
功能描述
io.close([file])
相当于file:close(),关闭默认的输出文件
io.flush()
相当于file:flush(),输出所有缓冲中的内容到默认输出文件
io.lines([filename])
若不带参数时io.lines()<=>io.input():lines();读取默认输入设备的内容,但结束时不关闭文件如:forlineinio.lines("main.lua")doprint(line)end
io.input([file])
io.output([file])
相当于io.input,但操作在默认输出文件上
io.read(…)
相当于io.input():read
io.write(…)
相当于io.output():write
io.tmpfile()
返回一个临时文件句柄,该文件以更新模式打开,程序结束时自动删除
io.type(obj)
检测obj是否一个可用的文件句柄;返回:"file":为一个打开的文件句柄"closedfile":为一个已关闭的文件句柄nil:
–print与io.write的不同–Write函数与print函数不同在于,write不附加任何额外的字符到输出中去,例如制表符,换行符等等。还有write函数是使用当前输出文件,而print始终使用标准输出。另外print函数会自动调用参数的tostring方法,所以可以显示出表(tables)函数(functions)和nil。print("hello", "Lua"); print("Hi")–> hello Lua–> Hiio.write("hello", "Lua"); io.write("Hi", "\n")–> helloLuaHi
— Opens a file in readlocal file = io.open("E:\\workplace\\project\\server\\script\\test\\src\\test.lua", "r")io.input(file)–设置当前文件为默认输出文件print(io.read())–默认读取第一行 –> –hello world,I is test.luaio.close(file)–关闭– Opens a file in append modefile = io.open("E:\\workplace\\project\\server\\script\\test\\src\\test.lua", "a")– sets the default output file as test.luaio.output(file)– appends a word test to the last line of the fileio.write("– End of the test.lua file\n")– closes the open fileio.close(file)–[[操作前–hello world,I is test.luaprint(123)–]]–[[操作后–hello world,I is test.luaprint(123)– End of the test.lua file–]]完全IO模式
"r"
是只读方式打开(默认),不能写入。
"w"
只写方式打开,不能读取。
"a"
追加打开一个现有的文件或进行追加创建一个新的文件模式。
"r+"
以读写方式打开,保留原有数据。这个模式是自由度最高的。
"w+"
以读写方式打开,删除原有数据。就是打开后文件是空文件。
"a+"
以读写方式打开,保留原有数据,只能在文件末尾添加,不能在文件中间改写数据。若找不到文件,也会创建新文件
"b"
某些系统支持二进制方式
正常情况下open函数返回一个文件的句柄。如果发生错误,则返回nil,以及一个错误信息和错误代码。
函数名
功能描述
io.open(filename[,mode])
按指定的模式打开一个文件,成功则返回文件句柄,失败则返回nil+错误信息
file:close()
关闭文件注:当文件句柄被垃圾收集后,文件将自动关闭。句柄将变为一个不可预知的值
file:flush()
向文件写入缓冲中的所有数据
file:lines()
返回一个迭代函数
如:forlineinfile:lines()dobodyend
file:read(…)
按指定的格式读取一个文件
file:write(…)
按指定的参数格式输出文件内容,参数必须为字符或数字,,若要输出其它值,则需通过
file:seek([whence][,offset])
于是渐渐开始有些伤怀。