解决方法
这个解决方案基于@PaulKulchenko的想法.
是的,这很麻烦:-)
是的,这很麻烦:-)
在io库中定义函数io.linesbackward(filename):
function io.linesbackward(filename) local file = assert(io.open(filename)) local chunk_size = 4*1024 local iterator = function() return "" end local tail = "" local chunk_index = math.ceil(file:seek"end" / chunk_size) return function() while true do local lineEOL,line = iterator() if lineEOL ~= "" then return line:reverse() end repeat chunk_index = chunk_index - 1 if chunk_index < 0 then file:close() iterator = function() error('No more lines in file "'..filename..'"',3) end return end file:seek("set",chunk_index * chunk_size) local chunk = file:read(chunk_size) local pattern = "^(.-"..(chunk_index > 0 and "\n" or "")..")(.*)" local new_tail,lines = chunk:match(pattern) iterator = lines and (lines..tail):reverse():gmatch"(\n?\r?([^\n]*))" tail = new_tail or chunk..tail until iterator end end end
用法:
local filename = "your_file.txt" print("--- backward: ---------------------------") for line in io.linesbackward(filename) do print(line) end print("--- forward: ----------------------------") for line in io.lines(filename) do print(line) end print("-----------------------------------------")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。