2016-06-21 46 views
4

而不是从前面读取文件,是否可以将其向后读取?这样输出就是从文件的后面到文件的前面。是否可以使用Lua“向后”读取文件?

编辑:最后一行显示第一,不完全倒退。

+0

完全向后,让你获得 'sdrawkcab'?或者只是最后一行显示? –

+0

是否需要O(n)时间复杂度? –

+0

@MarcB最后一行首先显示 – fishy

回答

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 

用法:

1

不使用标准库。但是,您可以始终通过线条从头到尾阅读它,将其存储在表格中,然后从最后一行“使用”到第一行。

4

这是可能的,但麻烦。 Lua API提供了​​函数来设置和获取读/写操作适用的文件中的位置。因此,您可以使用“seek”从最后一小块读取文件(例如,寻找filesize-1024位置,读取1024字节,查找所有行尾,打印完整行并存储剩下的),并继续这样做,回到文件的开头。主要优点是你不应该花费比你正在阅读的缓冲区多得多的内存(就像你从一开始就阅读,但是想以相反的顺序打印,你需要把整个文件放在内存中),但可能会很慢。

相关问题