package main import ( "archive/tar" "fmt" "io" "os" ) func main() { // Open a new tar file for writing file, err := os.Create("myarchive.tar") if err != nil { fmt.Println(err) return } defer file.Close() // Create a tar writer tarWriter := tar.NewWriter(file) defer tarWriter.Close() // Add three files to the tar archive files := []string{"file1.txt", "file2.txt", "file3.txt"} for _, filename := range files { // Get file info info, err := os.Stat(filename) if err != nil { fmt.Println(err) continue } // Create a new header for the file header := &tar.Header{ Name: filename, Size: info.Size(), Mode: int64(info.Mode()), ModTime: info.ModTime(), } // Write the header if err := tarWriter.WriteHeader(header); err != nil { fmt.Println(err) continue } // Open the file for reading file, err := os.Open(filename) if err != nil { fmt.Println(err) continue } defer file.Close() // Copy the file contents to the archive if _, err := io.Copy(tarWriter, file); err != nil { fmt.Println(err) continue } } }
package main import ( "archive/tar" "fmt" "io" "os" ) func main() { // Open the tar file for reading file, err := os.Open("myarchive.tar") if err != nil { fmt.Println(err) return } defer file.Close() // Create a new tar reader tarReader := tar.NewReader(file) // Read all files in the archive and extract them for { // Read the next file header header, err := tarReader.Next() if err == io.EOF { // EOF means we've reached the end of the archive break } if err != nil { fmt.Println(err) return } // Create a new file with the same name as in the archive file, err := os.Create(header.Name) if err != nil { fmt.Println(err) continue } defer file.Close() // Copy the file contents from the archive to the new file if _, err := io.Copy(file, tarReader); err != nil { fmt.Println(err) continue } fmt.Println("Extracted", header.Name) } }This example demonstrates how to read a tar archive and extract all the files. The program uses a tar reader's Next method to read each file header and create a new file with the same name. It then copies the file contents from the tar archive to the new file using io.Copy. Package library: archive/tar