dth981485742 2014-11-01 18:12
浏览 26
已采纳

在Go中解压缩tarball

For part of a program I'm writing I have a function for unpacking a tarball and returning a list of its content.

Everything appears to work except the extracted files are empty. I can extract the files content to stdout and see that it does give the correct content, just not sure why its not writing to the files.

The function:

func UnpackTarball(filename, extractpath string) ([]string, error) {
        buf, err := ioutil.ReadFile(filename)
        if err != nil {
                return nil, err
        }

        if err = os.MkdirAll(extractpath, os.ModeDir|0755); err != nil {
                return nil, err
        }

        tarball := tar.NewReader(bytes.NewReader(buf))
        contentlist := make([]string, 0, 500)

        // Iterate through the files in the archive
        for {
                hdr, err := tarball.Next()
                if err == io.EOF {
                        // end of tar archive
                        break
                }
                if err != nil {
                        return nil, err
                }

                info := hdr.FileInfo()
                entry := path.Join(extractpath, hdr.Name)

                // Is entry a directory?
                if info.IsDir() {
                        if err = os.MkdirAll(entry, os.ModeDir|0755); err != nil {
                                return nil, err
                        }
                        continue
                }

                // Append entry to the content list
                contentlist = append(contentlist, hdr.Name)
                // Create file
                f, err := os.Create(entry)
                if err != nil {
                        return nil, err
                }
                defer f.Close()

                _, err = io.Copy(bufio.NewWriter(f), tarball)
                //_, err = io.Copy(os.Stdout, tarball)
                if err != nil {
                        return nil, err
                }
        }
        return contentlist, nil
}

Thanks for any help.

  • 写回答

1条回答 默认 最新

  • doujun7161 2014-11-01 18:28
    关注

    You are not flushing the contents of the buffered writer and consequently you are not writing anything if the files are small enough. Place a call to bufio.(*Writer).Flush() somewhere after your io.Copy() call.

    Also, you might want to close the output files in the loop instead of deferring until all files have been written.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮