如何使用Lua 优雅并快速的读取一个文件的全部内容?
在这里我们可以看一下代码:
local open = io.open
local insert = table.insert
local concat = table.concat
function load_file(filename)
local file = open(filename, 'rb')
if not file then
return
end
local f = {}
for line in file:lines("l") do
insert(f, line)
end
file:close()
return concat(f, '\n')
end
print('file size = ', #load_file('filename'))
这里使用time命令行工具进行5次读取计时:
bogon:~ candy$ time lua main.lua
file size = 5570813
real 0m0.052s
user 0m0.037s
sys 0m0.013s
bogon:~ candy$ time lua main.lua
file size = 5570813
real 0m0.051s
user 0m0.037s
sys 0m0.012s
bogon:~ candy$ time lua main.lua
file size = 5570813
real 0m0.052s
user 0m0.037s
sys 0m0.012s
bogon:~ candy$ time lua main.lua
file size = 5570813
real 0m0.054s
user 0m0.038s
sys 0m0.014s
bogon:~ candy$ time lua main.lua
file size = 5570813
real 0m0.052s
user 0m0.037s
sys 0m0.012s
bogon:~ candy$