lua-文件操作
Lua I/O 库用于读取和处理文件。分为简单模式(和C一样)、完全模式。
简单模式在做一些简单的文件操作时较为合适。但是在进行一些高级的文件操作的时候,简单模式就显得力不从心。例如同时读取多个文件这样的操作,使用完全模式则较为合适。 打开文件操作语句如下: file = io.open (filename [, mode]) mode 的值有:
简单模式--简单模式使用标准的 I/O 或使用一个当前输入文件和一个当前输出文件。 -- 以只读方式打开文件file = io.open("E:test.lua","r") -- 设置默认输入文件为 test.lua io.input(file) -- 输出文件第一行 print(io.read()) -- 关闭打开的文件 io.close(file) -- 以附加的方式打开只写文件 file = io.open("E:test.lua","a") -- 设置默认输出文件为 test.lua io.output(file) -- 在文件最后一行添加 Lua 注释 io.write("-- ?E:test.lua 文件末尾注释") -- 关闭打开的文件 io.close(file) 在以上实例中我们使用了 io."x" 方法,其中 io.read() 中我们没有带参数,参数可以是下表中的一个:
其他的 io 方法有:
io.tmpfile():返回一个临时文件句柄,该文件以更新模式打开,程序结束时自动删除 完全模式-- 同一时间操作多个文件,我们需要使用 file:function_name 来代替 io.function_name 方法。-- 以追加的方式打开只写文件 function write(logfile,msg) local fd = io.open(logfile,"ab") if fd == nil then return end fd:write(msg) fd:flush() fd:close() end --读取文件所有内容 function read_all(filepath) ? ? local file = io.open(filepath,"r") ? ? if file==nil then ? ? ? ? return ? ? end ? ? t = {}? ? for line in file:lines() do ? ? ? ? table.insert(t,line) ? ? end ? ? file:close() ? ? return(t) end print("=============write data===============") local msg = "哈哈哈 ?hehen" write("E:test.lua",msg) print("write:"..msg) print("=============read data===============") line_t=read_all("E:test.lua") for _,line in pairs(line_t) do print(line) end read 的参数与简单模式一致。 其他方法:
以下实例使用了 seek 方法,定位到文件倒数第 25 个位置并使用 read 方法的 *a 参数,即从当期位置(倒数第 25 个位置)读取整个文件。 -- 以只读方式打开文件 file open"test.lua",0)"> "r" file:seek"end"25 fileread"*a")) 关闭打开的文件 fileclose() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |