package main import ( "archive/tar" "fmt" "io" "os" ) func main() { // Create a new tar archive file file, err := os.Create("example.tar") if err != nil { panic(err) } // Create a new tar writer tarWriter := tar.NewWriter(file) // Add files to the archive files := []string{"file1.txt", "file2.txt"} for _, filename := range files { // open the file to be added currentFile, err := os.Open(filename) if err != nil { panic(err) } // create the header for the file header := &tar.Header{ Name: filename, Size: info.Size(), } // write the header to the archive err = tarWriter.WriteHeader(header) if err != nil { panic(err) } // copy the file content to the archive _, err = io.Copy(tarWriter, currentFile) if err != nil { panic(err) } currentFile.Close() } // close the archive writer and file err = tarWriter.Close() if err != nil { panic(err) } file.Close() fmt.Println("Tar archive created successfully.") }
package main import ( "archive/tar" "fmt" "io" "os" ) func main() { // Open the tar archive file file, err := os.Open("example.tar") if err != nil { panic(err) } // Create a new tar reader tarReader := tar.NewReader(file) // Extract each file from archive for { header, err := tarReader.Next() if err == io.EOF { break } if err != nil { panic(err) } // create the file to be extracted extractedFile, err := os.Create(header.Name) if err != nil { panic(err) } // copy the file content to the new file _, err = io.Copy(extractedFile, tarReader) if err != nil { panic(err) } extractedFile.Close() fmt.Println("File extracted:", header.Name) } file.Close() }This code extracts all files from the "example.tar" archive file and saves them to their original file names. Both examples use the archive/tar package of the Go standard library.