dongou3158 2016-10-28 14:19
浏览 57
已采纳

将提取的tar.gz复制到单个文件

I am trying to copy the extracted content of a tar.gz to a single file in go lang. I will have only text inside the files.

The following is my current code.

f, err := os.Open(fullpath)
if err != nil {
    log.Panicf("Can not open file %s: %v", fullpath, err)
    return ""
}
defer f.Close()
reader, err := gzip.NewReader(f)
if err != nil{
    log.Panicf("Cannot read gzip archive %v", err);
    return ""
}
defer reader.Close()
tar_reader := tar.NewReader(reader)
var files []io.Reader
for{
    header, err := tar_reader.Next()
    if err == io.EOF {
        break
    } else if err != nil {
        log.Panicf("Cannot read file inside tarball %v", err);
        return 0, err
    } else {
        log.Println("Parsing file : ", header.Name)
        files = append(files, tar_reader)
    }
}
reader = io.MultiReader(files...)
writer, err := os.Create(target)
if err != nil {
    log.Panicf("Cannot write unarchived file %v", err);
    return 0, err
}
defer writer.Close()

result,err := io.Copy(writer, reader)
if(err != nil) {
    log.Panicf("Cannot write unarchived file %v", err);
}
return result,err

While I am not getting any error with the above code, the files are just not read. The output has no data. Please point me on where I am going wrong.

  • 写回答

1条回答 默认 最新

  • douyaju4259 2016-10-28 14:33
    关注

    You're appending the same tar.Reader over and over to the files slice. You have to read the file from the archive after you read the header. Just copy the files at that point. You probably should check for regular files too, vs directories, symlinks, etc.

    copied := 0
    for {
        header, err := tar_reader.Next()
        if err == io.EOF {
            break
        } else if err != nil {
            log.Fatalf("Cannot read file inside tarball %v", err)
        }
    
        if !(header.Typeflag == tar.TypeReg || header.Typeflag == tar.TypeRegA) {
            continue
        }
    
    
        n, err = io.Copy(writer, tar_reader)
        if err != nil {
            log.Fatalf("Cannot write unarchived file %v", err)
        }
        copied += n
    }
    return copied, nil
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?