How to extract files from a zip file using Lua?

后端 未结 3 1999
庸人自扰
庸人自扰 2021-01-12 18:24

How do I extract files using Lua?

Update: I now have the following code but it crashes every time it reaches the end of the function, but it successfully extracts al

3条回答
  •  天涯浪人
    2021-01-12 18:45

    It seems that you forgot to close currFile in the loop. I'm not sure why it crashes : maybe some sloppy resources management code or resource exhaustion (the number of files you can opened may be limited)...

    Anyway the correct code is :

    require "zip"
    
    function ExtractZipAndCopyFiles(zipPath, zipFilename, destinationPath)
    local zfile, err = zip.open(zipPath .. zipFilename)
    
    -- iterate through each file insize the zip file
    for file in zfile:files() do
        local currFile, err = zfile:open(file.filename)
        local currFileContents = currFile:read("*a") -- read entire contents of current file
        local hBinaryOutput = io.open(destinationPath .. file.filename, "wb")
    
        -- write current file inside zip to a file outside zip
        if(hBinaryOutput)then
            hBinaryOutput:write(currFileContents)
            hBinaryOutput:close()
        end
        currFile.close()
    end
    
    zfile:close()
    end
    

提交回复
热议问题