要将文件读入字节数组a
,我一直在使用以下代码:
file = io.open(fileName, "rb")
str = file:read("*a")
a = {str:byte(1, #str)}
虽然这适用于较小的文件,但str:byte
对于 1MB 的文件则失败,给出stack overflow (string slice too long)
.
是否有另一种方法可以成功读取这些较大的文件?
local fileName = 'C:\\Program Files\\Microsoft Office\\Office12\\excel.exe'
local file = assert(io.open(fileName, 'rb'))
local t = {}
repeat
local str = file:read(4*1024)
for c in (str or ''):gmatch'.' do
t[#t+1] = c:byte()
end
until not str
file:close()
print(#t) --> 18330984
在使用 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
这会将文件中的每block
(1) 个字节存储file.txt
到表中bytes
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()