mirror of
https://github.com/EngineerSmith/nativefs.git
synced 2025-11-08 23:15:02 +00:00
close file after nativefs.lines() finishes
This commit is contained in:
30
nativefs.lua
30
nativefs.lua
@@ -120,19 +120,16 @@ function File:read(containerOrBytes, bytes)
|
|||||||
return data, r
|
return data, r
|
||||||
end
|
end
|
||||||
|
|
||||||
function File:lines()
|
local function lines(file, autoclose)
|
||||||
if self._mode ~= 'r' then error("File is not opened for reading") end
|
|
||||||
|
|
||||||
local BUFFERSIZE = 4096
|
local BUFFERSIZE = 4096
|
||||||
local buffer = ByteArray(BUFFERSIZE)
|
local buffer, bufferPos = ByteArray(BUFFERSIZE), 0
|
||||||
local bytesRead = tonumber(C.fread(buffer, 1, BUFFERSIZE, self._handle))
|
local bytesRead = tonumber(C.fread(buffer, 1, BUFFERSIZE, file._handle))
|
||||||
|
|
||||||
local bufferPos = 0
|
local offset = file:tell()
|
||||||
local offset = self:tell()
|
|
||||||
return function()
|
return function()
|
||||||
local line = {}
|
file:seek(offset)
|
||||||
self:seek(offset)
|
|
||||||
|
|
||||||
|
local line = {}
|
||||||
while bytesRead > 0 do
|
while bytesRead > 0 do
|
||||||
for i = bufferPos, bytesRead - 1 do
|
for i = bufferPos, bytesRead - 1 do
|
||||||
if buffer[i] == 10 then -- end of line
|
if buffer[i] == 10 then -- end of line
|
||||||
@@ -145,12 +142,21 @@ function File:lines()
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
bytesRead = tonumber(C.fread(buffer, 1, BUFFERSIZE, self._handle))
|
bytesRead = tonumber(C.fread(buffer, 1, BUFFERSIZE, file._handle))
|
||||||
offset, bufferPos = offset + bytesRead, 0
|
offset, bufferPos = offset + bytesRead, 0
|
||||||
end
|
end
|
||||||
|
|
||||||
return line[1] and table.concat(line) or nil
|
if not line[1] then
|
||||||
|
if autoclose then file:close() end
|
||||||
|
return nil
|
||||||
end
|
end
|
||||||
|
return table.concat(line)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
function File:lines()
|
||||||
|
if self._mode ~= 'r' then error("File is not opened for reading") end
|
||||||
|
return lines(self)
|
||||||
end
|
end
|
||||||
|
|
||||||
function File:write(data, size)
|
function File:write(data, size)
|
||||||
@@ -282,7 +288,7 @@ function nativefs.lines(name)
|
|||||||
local f = nativefs.newFile(name)
|
local f = nativefs.newFile(name)
|
||||||
local ok, err = f:open('r')
|
local ok, err = f:open('r')
|
||||||
if not ok then return nil, err end
|
if not ok then return nil, err end
|
||||||
return f:lines()
|
return lines(f, true)
|
||||||
end
|
end
|
||||||
|
|
||||||
function nativefs.load(name)
|
function nativefs.load(name)
|
||||||
|
|||||||
Reference in New Issue
Block a user