file:write()的写入顺序问题
lua吧
全部回复
仅看楼主
level 3
tolog = function(str)
local file = io.open("log.txt","a")
str = "["..os.date().."]: "..str.."\n"
file:write(str)
end
for i = 1 ,100000000 ,1 do
if math.mod(i,1000) == 0 then
tolog(i+x)
end
end
代码,以上,输出的log.txt
[11/25/13 11:58:10]: 8000
[11/25/13 11:58:10]: 7000
[11/25/13 11:58:10]: 6000
[11/25/13 11:58:10]: 5000
[11/25/13 11:58:10]: 4000
[11/25/13 11:58:10]: 3000
[11/25/13 11:58:10]: 2000
[11/25/13 11:58:10]: 1000
[11/25/13 11:58:10]: 11000
[11/25/13 11:58:10]: 10000
[11/25/13 11:58:10]: 9000
这是为啥啊?这顺序是什么情况?求大神指点一下
2013年11月25日 04点11分 1
level 12
lua 文档里说了
Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen.
于是别偷懒,自己 file:close()
2013年11月26日 01点11分 2
哦哦哦,知道了,那这样会不会产生严重的效率问题啊?
2013年11月29日 01点11分
level 8
这是因为文件都是先写到缓冲区的,当文件句柄关闭时才写入文件。你这里每一行记录对应一个句柄,这些句柄在被垃圾回收时才关闭,而垃圾回收时关闭这些句柄是不按照句柄的创建顺序来关的,所以顺序就乱了。
2013年11月26日 14点11分 3
恩,那我就懂了,怪不得写了死循环的时候,一条日志都输出不来,原来没有回收时机就不会写日志,是吧?
2013年11月29日 01点11分
1