如何在Lua中只读取文本文件的最后一行? [英] How to Read only the last line of a text file in Lua?

查看:1335
本文介绍了如何在Lua中只读取文本文件的最后一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序可以生成文本文件,大小可以达到20M。有时候我只关心文件的最后一行,有没有一种方法可以读取文件的其余部分,而不用浪费内存呢?

解决方案

我可能会误解,但不会诉诸一些欺骗,看来你不能。
然而,如果你对线的长度有一个粗略的估计,你可以打开一个文件,然后从最后找出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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆