在Lua中读取整个文件

Hen*_*gen 18 io lua

我想读取一个完整的mp3文件,以便读出id3标签.就在那时我注意到那个文件:read("*a")显然不会读取整个文件而是一小部分.所以我尝试构建某种解决方法以获取整个文件的内容:

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
Run Code Online (Sandbox Code Playgroud)

对于我的testfile,这表明执行了256次读取操作,总共读取了~113kB(整个文件大约为7MB).虽然这应该足以读取大多数id3标签,但我想知道为什么Lua会以这种方式运行(特别是因为它在读取大型基于文本的文件时不会,例如*.oj或*.ase).是否有任何解释这种行为或可能是一个可靠的读取整个文件的解决方案?

lhf*_*lhf 53

我必须遗漏一些东西,但我不明白为什么需要一个循环.这应该工作(但是如果无法打开文件,你最好添加错误处理):

function readAll(file)
    local f = assert(io.open(file, "rb"))
    local content = f:read("*all")
    f:close()
    return content
end
Run Code Online (Sandbox Code Playgroud)

  • 正如在我的问题的评论中可以看到的,@daurnimator 已经发现问题是缺少 b,但无论如何还是感谢您的回答:) 编辑:我将您的答案标记为已接受,以便向人们表明我的问题已得到解决。 (2认同)