title: Golang: append file to an existing tar archive
body: <p>How would I append a file to an existing tar archive in Go?  I don't see anything obvious in the <a href="http://golang.org/pkg/archive/tar/" rel="nofollow">docs</a> on how to do it.</p>
  
  <p>I have a tar file that has already been created and I want to add more to it after it has already been closed.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Altering the example in the docs and following the answer given, I'm still not getting the expected result.  The first three files are being written to the tar but when I close and open up the file again to write to it, the new file is never being written.  The code runs fine. I don't know what I'm missing.</p>
  
  <p>The following code gives me a tar file with three files in it: readme.txt, gopher.txt, todo.txt.  foo.bar never gets written.</p>
  
  <pre><code>package main
  
  import (
      "archive/tar"
      "log"
      "os"
  )
  
  func main() {
      f, err := os.Create("/home/jeff/Desktop/test.tar")
      if err != nil {
          log.Fatalln(err)
      }
  
      tw := tar.NewWriter(f)
  
      var files = []struct {
          Name, Body string
      }{
          {"readme.txt", "This archive contains some text files."},
          {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
          {"todo.txt", "Get animal handling licence."},
      }
      for _, file := range files {
          hdr := &amp;tar.Header{
              Name: file.Name,
              Size: int64(len(file.Body)),
          }
          if err := tw.WriteHeader(hdr); err != nil {
              log.Fatalln(err)
          }
          if _, err := tw.Write([]byte(file.Body)); err != nil {
              log.Fatalln(err)
          }
      }
      if err := tw.Close(); err != nil {
          log.Fatalln(err)
      }
      f.Close()
  
      // Open up the file and append more things to it
  
      f, err = os.OpenFile("/home/jeff/Desktop/test.tar", os.O_APPEND|os.O_WRONLY, os.ModePerm)
      if err != nil {
          log.Fatalln(err)
      }
      tw = tar.NewWriter(f)
  
      test := "this is a test"
  
      hdr := &amp;tar.Header{
          Name: "foo.bar",
          Size: int64(len(test)),
      }
  
      if err := tw.WriteHeader(hdr); err != nil {
          log.Fatalln(err)
      }
  
      if _, err := tw.Write([]byte(test)); err != nil {
          log.Fatalln(err)
      }
  
      if err := tw.Close(); err != nil {
          log.Fatalln(err)
      }
      f.Close()
  
  }
  </code></pre>