在Lua中读取整个文件 [英] Reading whole files in Lua

查看:192
本文介绍了在Lua中读取整个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取完整的mp3文件,以便读出id3标签。就在那时我注意到那个文件: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会以这种方式运行(特别是因为它在读取大型基于文本的文件时不会出现这种情况,例如* .oj或* .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 *.oj 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆