To open and read data from a compressed file in Go, you can use the compress/gzip
package.
Here's an example code snippet to demonstrate how to open and read a gzip compressed file:
package main
import (
"compress/gzip"
"fmt"
"io"
"log"
"os"
)
func main() {
// Open the compressed file
file, err := os.Open("file.gz")
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Create a gzip reader
reader, err := gzip.NewReader(file)
if err != nil {
log.Fatal(err)
}
defer reader.Close()
// Read and print the uncompressed data
buf := make([]byte, 1024)
for {
n, err := reader.Read(buf)
if err != nil && err != io.EOF {
log.Fatal(err)
}
if n == 0 {
break
}
fmt.Print(string(buf[:n]))
}
}
In the above code, replace "file.gz"
with the path to your actual compressed file. The code uses os.Open
to open the file and then creates a gzip.NewReader
to read the compressed data. The data is read in chunks using the reader.Read
function, and the uncompressed data is printed to the console.
Make sure to import the required packages compress/gzip
, fmt
, io
, and log
.