代码之家  ›  专栏  ›  技术社区  ›  Brian T Hannan

为什么lua在解压缩zip文件后会崩溃?

  •  1
  • Brian T Hannan  · 技术社区  · 15 年前

    我有下面的代码,但每次到达函数末尾时都会崩溃,但它成功地提取了所有文件并将它们放在正确的位置。

    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
        end
    
        zfile:close()
    end
    -- call the function
    ExtractZipAndCopyFiles("C:\\Users\\bhannan\\Desktop\\LUA\\", "example.zip", "C:\\Users\\bhannan\\Desktop\\ZipExtractionOutput\\")
    

    2 回复  |  直到 15 年前
        1
  •  2
  •   Doug Currie    15 年前

    也许你需要打电话 currFile:close() 之后 currFile:read() 在每次迭代中?

        2
  •  2
  •   Judge Maygarden    15 年前

    问题是LuaZip不会遍历所有打开的内部文件,并在关闭包含这些文件的打开zip文件之前关闭它们。因此,当垃圾收集器试图关闭内部文件时,系统会崩溃,而这些文件已经被从它们下面拉出了地毯。所以,只需移除 zfile:close() userdata 按与分配相反的顺序。