Help us understand the problem. What is going on with this article?

Goでtar.gzを出力する

勉強用にtar.gzのサンプルを作りました。ソースコード自身をtar.gzに格納圧縮し、そのバイト列を標準出力に表示し、output.tar.gzに保存し、終了します。bytes.Buffer、gzip.Writer、tar.Writerは全てio.Writerインターフェースを実装しているので順番に噛み合わせてtar.gzされたバイト列を出力できます。

ソース

tar.gz.go
package main

import (
    "archive/tar"
    "bytes"
    "compress/gzip"
    "fmt"
    "io"
    "os"
)

func writefile(w *tar.Writer,name string){
    if file, err := os.Open(name) ; err == nil{
        fi, _:=file.Stat()
        hdr := new(tar.Header)
        hdr.Size=fi.Size()
        hdr.Name=fi.Name()
        w.WriteHeader(hdr)
        io.Copy(w, file)
        file.Close()
    }
}
func main() {
    var buf bytes.Buffer
    gz := gzip.NewWriter(&buf)
    tw := tar.NewWriter(gz)
    writefile(tw,"tar.gz.go")
    tw.Close()
    gz.Close()
    data:=buf.Bytes()
    fmt.Print(data)
    if file, err := os.Create("output.tar.gz") ; err == nil{
        file.Write(data)
        file.Close()
    }
}

補足

  • 1ファイルならtarする必要がないよね
    • そのとおりです。実際はwritefile()を複数呼んでファイルを追加します。
  • 直接ファイルに書き込めばいいのでは?
    • 圧縮後の中身を見たかったので一度バイト列に出力しました。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした