File io 在Lua中,如何将文件读入字节数组?

File io 在Lua中,如何将文件读入字节数组?,file-io,lua,File Io,Lua,要将文件读入字节数组a,我使用了以下代码: file = io.open(fileName, "rb") str = file:read("*a") a = {str:byte(1, #str)} 虽然这适用于较小的文件,str:byte对于1MB文件失败,导致堆栈溢出(字符串片太长) 是否有其他方法可以成功读取这些较大的文件?这将把文件file.txt中的每个块(1)字节存储到表字节中 local bytes = {} file = assert(io.open("file.txt","rb

要将文件读入字节数组
a
,我使用了以下代码:

file = io.open(fileName, "rb")
str = file:read("*a")
a = {str:byte(1, #str)}
虽然这适用于较小的文件,
str:byte
对于1MB文件失败,导致
堆栈溢出(字符串片太长)


是否有其他方法可以成功读取这些较大的文件?

这将把文件
file.txt
中的每个
(1)字节存储到表
字节中

local bytes = {}
file = assert(io.open("file.txt","rb"))
block = 1 --blocks of 1 byte
while true do
    local byte = file:read(block)
    if byte == nil then
        break
    else
        bytes[#bytes+1] = string.byte(byte)
    end
end
file:close()

在使用LuaJIT的情况下,另一种方法是读取字节块并将其转换为C数组。如果一次性读取整个文件,缓冲区应该分配足够的内存来存储它(文件大小字节)。另外,可以分块读取文件,并为每个块重用缓冲区

使用C缓冲区的优点是,它比将字节块转换为Lua字符串或Lua表更高效、更节省内存。缺点是FFI仅在LuaJIT中受支持

local ffi = require("ffi")

-- Helper function to calculate file size.
local function filesize (fd)
   local current = fd:seek()
   local size = fd:seek("end")
   fd:seek("set", current)
   return size
end

local filename = "example.bin"

-- Open file in binary mode.
local fd, err = io.open(filename, "rb")
if err then error(err) end

-- Get size of file and allocate a buffer for the whole file.
local size = filesize(fd)
local buffer = ffi.new("uint8_t[?]", size)

-- Read whole file and store it as a C buffer.
ffi.copy(buffer, fd:read(size), size)
fd:close()

-- Iterate through buffer to print out contents.
for i=0,size-1 do
   io.write(buffer[i], " ")
end

为什么要将内容放入字节数组中?您可以很容易地从字符串中提取每个字节。为什么它是4*1024?@Coal-与磁盘扇区和内存页对齐。
local ffi = require("ffi")

-- Helper function to calculate file size.
local function filesize (fd)
   local current = fd:seek()
   local size = fd:seek("end")
   fd:seek("set", current)
   return size
end

local filename = "example.bin"

-- Open file in binary mode.
local fd, err = io.open(filename, "rb")
if err then error(err) end

-- Get size of file and allocate a buffer for the whole file.
local size = filesize(fd)
local buffer = ffi.new("uint8_t[?]", size)

-- Read whole file and store it as a C buffer.
ffi.copy(buffer, fd:read(size), size)
fd:close()

-- Iterate through buffer to print out contents.
for i=0,size-1 do
   io.write(buffer[i], " ")
end