如何在Lua中只读取文本文件的最后一行? [英] How to Read only the last line of a text file in Lua?
问题描述
我可能会误解,但不会诉诸一些欺骗,看来你不能。
然而,如果你对线的长度有一个粗略的估计,你可以打开一个文件,然后从最后找出1Kb。
<$ p
本地len = f:seek(end)$ b $本地f = io.open([[c:\ test_file.txt] b
f:seek(set,len - 1024)
本地文本= f:read(* a)
print(string.match(text,[ ^%c] * $))
f:close()
考虑到这种模式需要一些改进。它目前假定没有控制字符出现在一行上。如果你的行有选项卡,那么它将从那里捕获,直到文件结束。
I have a program that generates text fiels that can be up to 20 mets in size. Sometimes I only care about the last line in the file, is there a way to read just that line with out wasting memory reading the rest of the file?
I could be mistaken but without resorting to some trickery, it seems that you can't. However, if you have a rough estimate of the length of the lines, you can open a file and then seek from the end, say, 1Kb.
local f = io.open([[c:\test_file.txt]], "r")
local len = f:seek("end")
f:seek("set", len - 1024)
local text = f:read("*a")
print(string.match(text, "[^%c]*$"))
f:close()
Hope this helps. Take into account that the pattern needs some refinement. It currently assumes that no control characters appear on a line. If your line has i.e. tabs, then it will capture from there till the end of file.
这篇关于如何在Lua中只读取文本文件的最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!