Lua中的文件操作(io,dofile函数)

demo.lua

print("11111111111")
dofile("./src/main.lua")  --执行Lua脚本文件


main.lua

local function fileRW()
	print("22222222222")
	------------------------------------------------------------
	---------------------READ FILE------------------------------
	------------------------------------------------------------
	local rfile = io.open("./src/demoR.txt","r")
	rfile:setvbuf("full",100) --设定缓冲区大小
	local line
	line = rfile:read()
	print(line)
	print("-------------------")
	for line in rfile:lines() do --lines()在每次调用时,迭代的返回新的一行,read()方法的增强迭代版
		print(line)
	end
	rfile:flush() --将缓冲区中的内容强制输出
	------------------------------------------------------------
	-------------------WRITE FILE-------------------------------
	------------------------------------------------------------
	local wfile = io.open("./src/demoW.txt","w")
	local i
	for i = 1, 5 do   --写五行字符串进入文件
		wfile:write("write something...\n")
	end
	------------------------------------------------------------
	-------------------READ/WRITE FILE--------------------------
	------------------------------------------------------------
	rfile:setvbuf("no",0)   --无缓冲模式
	rfile = io.open("./src/demoR.txt","r")	
	for line in rfile:lines() do 
		wfile:write(line)
	end	
	
	rfile:close() --关闭文件句柄
	wfile:close()
end

fileRW()  --执行函数


运行结果及截图

11111111111
22222222222
abcdefg~~~~
-------------------
Hello~Lua
Hello~World!



 

posted @ 2013-11-28 10:17  Mr轨迹  阅读(2578)  评论(0编辑  收藏  举报