在 Lua 中读取整个文件 [英] Reading whole files in Lua
问题描述
我正在尝试读取完整的 mp3 文件以读出 id3 标签.那时我注意到 file:read("*a") 显然没有读取完整文件,而是读取了一小部分.因此,我尝试构建某种解决方法以获取整个文件的内容:
I am trying to read a full mp3 file in order to read out the id3 tags. That's when I noticed that file:read("*a") apparently does not read the full file but rather a small part. So I tried to build some kind of workaround in order to get the content of the whole file:
function readAll(file)
local f = io.open(file, "r")
local content = ""
local length = 0
while f:read(0) ~= "" do
local current = f:read("*all")
print(#current, length)
length = length + #current
content = content .. current
end
return content
end
对于我的测试文件,这表明执行了 256 次读取操作,总共读取了 ~113kB(整个文件为 ~7MB).虽然这应该足以读取大多数 id3 标签,但我想知道为什么 Lua 会以这种方式运行(尤其是因为它在读取大型文本文件(例如 *.obj 或 *.ase)时不会这样做).这种行为是否有任何解释,或者是否有可靠读取整个文件的解决方案?
for my testfile, this shows that 256 reading operations are performed, reading a total of ~113kB (the whole file is ~7MB). Though this should be enough to read most id3 tags, I wonder why Lua behaves in this way (especially because it does not when reading large textbased files such as *.obj or *.ase). Is there any explanation for this behaviour or maybe a solution to reliably read the whole file?
推荐答案
我一定遗漏了一些东西,但我不明白为什么需要循环.这应该可以工作(但您最好添加错误处理,以防文件无法打开):
I must be missing something but I fail to see why a loop is needed. This should work (but you'd better add error handling in case the file cannot be opened):
function readAll(file)
local f = assert(io.open(file, "rb"))
local content = f:read("*all")
f:close()
return content
end
这篇关于在 Lua 中读取整个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!