[Lua]Lua IO库整理
| 
                         I/O库为文件操作提供了两种不同的模型,简单模型和完整模型。简单模型假设有一个当前输入文件和一个当前输出文件,它的I/O操作均作用于这些文件。完整模型则使用显式地文件句柄。它采用了面向对象的风格,并将所有的操作定义为文件句柄上的方法。? 简单IO模式简单模型的所有操作都作用于两个当前文件。I/O库将当前输入文件初始化为进程标准输入(stdin),将当前输出文件初始化为进程标准输出。在执行io.read()操作时,就会从标准输入中读取一行。 用函数io.input和io.output可以改变这两个当前文件。io.input(filename)调用会以只读模式打开指定的文件,并将其设定为当前输入文件;除非再次调用io.input,否则所有的输入都将来源于这个文件;在输出方面,io.output也可以完成类似的工作 
 ?io.write,?io.read?是一对.默认情况下,他们从stdin读输入,输出到stdout。?另有两个函数可以改变这一默认行为:?io.input("xx"),?io.output("yy")?他们改变输入为某个?xx?文件,?输出到?yy?文件。?eg: 
 如果?io.read()参数 
 --[[test.lua的内容
hello world,I is test.lua
print(123)
--]]
 io.input("E:workplaceprojectserverscripttestsrctest.lua")
 t=io.read("*all")
 io.write(t,'n')  ------输出整个 test.lua 文件的内容到 stdin
--> --hello world,I is test.lua
--> print(123) 
 --print与io.write的不同
--Write函数与print函数不同在于,write不附加任何额外的字符到输出中去,例如制表符,换行符等等。还有write函数是使用当前输出文件,而print始终使用标准输出。另外print函数会自动调用参数的tostring方法,所以可以显示出表(tables)函数(functions)和nil。
print("hello","Lua"); 
print("Hi")
--> hello   Lua
--> Hi
io.write("hello","Lua"); 
io.write("Hi","n")
--> helloLuaHi 
-- Opens a file in read
local file = io.open("E:workplaceprojectserverscripttestsrctest.lua","r")
io.input(file)--设置当前文件为默认输出文件
print(io.read())--默认读取第一行 
--> --hello world,I is test.lua
io.close(file)--关闭
-- Opens a file in append mode
file = io.open("E:workplaceprojectserverscripttestsrctest.lua","a")
-- sets the default output file as test.lua
io.output(file)
-- appends a word test to the last line of the file
io.write("-- End of the test.lua filen")
-- closes the open file
io.close(file)
--[[操作前
--hello world,I is test.lua
print(123)
--]]
--[[操作后
--hello world,I is test.lua
print(123)-- End of the test.lua file
--]] 
完全IO模式简单I/O功能太受限了,以至于基本没有什么用处,而用的更多的则是这里说的完整I/O模型。完整I/O模型可以进行更多的I/O控制,它是基于文件句柄的,就好比与C语言中的FILE*,表示一个正在操作的文件。 要打开一个文件,可以使用io.open函数,它有两个参数,一个表示要打开的文件名,另一个表示操作的模式字符串。模式字符串可以有以下四种取值方式:io.open(filename,[mode])的mode取值 
 正常情况下open函数返回一个文件的句柄。如果发生错误,则返回nil,以及一个错误信息和错误代码。?? 当成功打开一个文件以后,就可以使用read/write方法读写文件了,这与read/write函数相似,但是需要用冒号语法,将它们作为文件句柄的方法来调用 
 ? -- Opens a file in read mode
file = io.open("E:workplaceprojectserverscripttestsrctest.lua","r")
-- prints the first line of the file
print(file:read())
--> --hello world,I is test.lua
-- closes the opened file
file:close()
-- Opens a file in append mode
file = io.open("E:workplaceprojectserverscripttestsrctest.lua","a")
-- appends a word test to the last line of the file
file:write("--testn")
-- closes the open file
file:close()
--[[操作前
--hello world,I is test.lua
print(123)-- End of the test.lua file
--]]
--[[操作后
--hello world,I is test.lua
print(123)-- End of the test.lua file
--test
--]]
        (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
