github.com/freddyisaac/sicortex-golang@v0.0.0-20231019035217-e03519e66f60/src/archive/tar/example_test.go (about)

     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() {
    17  	// Create a buffer to write our archive to.
    18  	buf := new(bytes.Buffer)
    19  
    20  	// Create a new tar archive.
    21  	tw := tar.NewWriter(buf)
    22  
    23  	// Add some files to the archive.
    24  	var files = []struct {
    25  		Name, Body string
    26  	}{
    27  		{"readme.txt", "This archive contains some text files."},
    28  		{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
    29  		{"todo.txt", "Get animal handling license."},
    30  	}
    31  	for _, file := range files {
    32  		hdr := &tar.Header{
    33  			Name: file.Name,
    34  			Mode: 0600,
    35  			Size: int64(len(file.Body)),
    36  		}
    37  		if err := tw.WriteHeader(hdr); err != nil {
    38  			log.Fatalln(err)
    39  		}
    40  		if _, err := tw.Write([]byte(file.Body)); err != nil {
    41  			log.Fatalln(err)
    42  		}
    43  	}
    44  	// Make sure to check the error on Close.
    45  	if err := tw.Close(); err != nil {
    46  		log.Fatalln(err)
    47  	}
    48  
    49  	// Open the tar archive for reading.
    50  	r := bytes.NewReader(buf.Bytes())
    51  	tr := tar.NewReader(r)
    52  
    53  	// Iterate through the files in the archive.
    54  	for {
    55  		hdr, err := tr.Next()
    56  		if err == io.EOF {
    57  			// end of tar archive
    58  			break
    59  		}
    60  		if err != nil {
    61  			log.Fatalln(err)
    62  		}
    63  		fmt.Printf("Contents of %s:\n", hdr.Name)
    64  		if _, err := io.Copy(os.Stdout, tr); err != nil {
    65  			log.Fatalln(err)
    66  		}
    67  		fmt.Println()
    68  	}
    69  
    70  	// Output:
    71  	// Contents of readme.txt:
    72  	// This archive contains some text files.
    73  	// Contents of gopher.txt:
    74  	// Gopher names:
    75  	// George
    76  	// Geoffrey
    77  	// Gonzo
    78  	// Contents of todo.txt:
    79  	// Get animal handling license.
    80  }