doutonghang2761 2017-04-27 04:57
浏览 62
已采纳

如何在Golang的tar文件中放入tar文件

I want to create a tar file and inside that tar file I want to put other tar files.Hierarchy is something like

TopLevelTar.tar.gz
    |-->primary/primary.tar
    |-->secondary/secondaty.tar
    |-->tertiary/tertiary.tar

How can I do it in golag?

  • 写回答

2条回答 默认 最新

  • duancai9010 2017-04-27 09:56
    关注

    I think this might help you. Basically, this solution is creating a tarball from multiple files. You have to simply give path of your files in place of a.go and b.go etc.

    package main
    
    import (
        "archive/tar"
        "compress/gzip"
        "io"
        "log"
        "os"
    )
    
    func addFile(tw *tar.Writer, path string) error {
        file, err := os.Open(path)
        if err != nil {
            return err
        }
        defer file.Close()
        if stat, err := file.Stat(); err == nil {
            // now lets create the header as needed for this file within the tarball
            header := new(tar.Header)
            header.Name = path
            header.Size = stat.Size()
            header.Mode = int64(stat.Mode())
            header.ModTime = stat.ModTime()
            // write the header to the tarball archive
            if err := tw.WriteHeader(header); err != nil {
                return err
            }
            // copy the file data to the tarball
            if _, err := io.Copy(tw, file); err != nil {
                return err
            }
        }
        return nil
    }
    
    func main() {
        // set up the output file
        file, err := os.Create("output.tar.gz")
        if err != nil {
            log.Fatalln(err)
        }
        defer file.Close()
        // set up the gzip writer
        gw := gzip.NewWriter(file)
        defer gw.Close()
        tw := tar.NewWriter(gw)
        defer tw.Close()
        // grab the paths that need to be added in
        paths := []string{
            "a.go",
            "b.go",
        }
        // add each file as needed into the current tar archive
        for i := range paths {
            if err := addFile(tw, paths[i]); err != nil {
                log.Fatalln(err)
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案