2016-06-21 45 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字節,查找所有行尾,打印完整行並存儲剩下的),並繼續這樣做,回到文件的開頭。主要優點是你不應該花費比你正在閱讀的緩衝區多得多的內存(就像你從一開始就閱讀,但是想以相反的順序打印,你需要把整個文件放在內存中),但可能會很慢。

相關問題