Lua能否实现向后读取文件内容的功能?
- 内容介绍
- 文章标签
- 相关推荐
本文共计322个文字,预计阅读时间需要2分钟。
不是从前端读取文件,而是否可以向后端读取它?这样的输出就是从文件后面到文件前面的。编辑:最后一行显示,而不是完整地向后。这个解决方案基于@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("-----------------------------------------")
本文共计322个文字,预计阅读时间需要2分钟。
不是从前端读取文件,而是否可以向后端读取它?这样的输出就是从文件后面到文件前面的。编辑:最后一行显示,而不是完整地向后。这个解决方案基于@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("-----------------------------------------")

