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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥200 csgo2的viewmatrix值是否还有别的获取方式
  • ¥15 Stable Diffusion,用Ebsynth utility在视频选帧图重绘,第一步报错,蒙版和帧图没法生成,怎么处理啊
  • ¥15 请把下列每一行代码完整地读懂并注释出来
  • ¥15 pycharm运行main文件,显示没有conda环境
  • ¥15 易优eyoucms关于二级栏目调用的问题
  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?
  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集
  • ¥15 特定网页无法访问,已排除网页问题