Golang : Gunzip file
This tutorial demonstrates how to g-unzip a gz
file easily in Golang. It is a continuation from previous tutorial on how to unzip a zip archive.
gunzip.go
package main
import (
"compress/gzip"
"flag"
"fmt"
"io"
"os"
"strings"
)
func main() {
flag.Parse() // get the arguments from command line
filename := flag.Arg(0)
if filename == "" {
fmt.Println("Usage : gunzip sourcefile.gz")
os.Exit(1)
}
gzipfile, err := os.Open(filename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
reader, err := gzip.NewReader(gzipfile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer reader.Close()
newfilename := strings.TrimSuffix(filename, ".gz")
writer, err := os.Create(newfilename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer writer.Close()
if _, err = io.Copy(writer, reader); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
Outputs (example) :
./gunzip
Usage : gunzip sourcefile.gz
This program will not produce any message upon successful decompression of gzipped file.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.6k Golang : Shuffle strings array
+4.2k Golang *File points to a file or directory ?
+10.5k Golang : Find and draw contours with OpenCV example
+18.3k Golang : Count JSON objects and convert to slice/array
+8.7k Golang : Sort and reverse sort a slice of floats
+5.3k Golang : Map within a map example
+8k Golang : Serving HTTP and Websocket from different ports in a program example
+25.7k Golang : Find files by name - cross platform example
+16.5k Golang : Put UTF8 text on OpenCV video capture image frame
+6.5k Golang : What fmt.Println() can do and println() cannot do
+6.4k Golang : Individual and total number of words counter example