Home | History | Annotate | Download | only in tar
      1 // Copyright 2013 The Go Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style
      3 // license that can be found in the LICENSE file.
      4 
      5 package tar_test
      6 
      7 import (
      8 	"archive/tar"
      9 	"bytes"
     10 	"fmt"
     11 	"io"
     12 	"log"
     13 	"os"
     14 )
     15 
     16 func Example_minimal() {
     17 	// Create and add some files to the archive.
     18 	var buf bytes.Buffer
     19 	tw := tar.NewWriter(&buf)
     20 	var files = []struct {
     21 		Name, Body string
     22 	}{
     23 		{"readme.txt", "This archive contains some text files."},
     24 		{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
     25 		{"todo.txt", "Get animal handling license."},
     26 	}
     27 	for _, file := range files {
     28 		hdr := &tar.Header{
     29 			Name: file.Name,
     30 			Mode: 0600,
     31 			Size: int64(len(file.Body)),
     32 		}
     33 		if err := tw.WriteHeader(hdr); err != nil {
     34 			log.Fatal(err)
     35 		}
     36 		if _, err := tw.Write([]byte(file.Body)); err != nil {
     37 			log.Fatal(err)
     38 		}
     39 	}
     40 	if err := tw.Close(); err != nil {
     41 		log.Fatal(err)
     42 	}
     43 
     44 	// Open and iterate through the files in the archive.
     45 	tr := tar.NewReader(&buf)
     46 	for {
     47 		hdr, err := tr.Next()
     48 		if err == io.EOF {
     49 			break // End of archive
     50 		}
     51 		if err != nil {
     52 			log.Fatal(err)
     53 		}
     54 		fmt.Printf("Contents of %s:\n", hdr.Name)
     55 		if _, err := io.Copy(os.Stdout, tr); err != nil {
     56 			log.Fatal(err)
     57 		}
     58 		fmt.Println()
     59 	}
     60 
     61 	// Output:
     62 	// Contents of readme.txt:
     63 	// This archive contains some text files.
     64 	// Contents of gopher.txt:
     65 	// Gopher names:
     66 	// George
     67 	// Geoffrey
     68 	// Gonzo
     69 	// Contents of todo.txt:
     70 	// Get animal handling license.
     71 }
     72