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
+5.4k Fix fatal error: evacuation not done in time problem
+18.3k Golang : Write file with io.WriteString
+13.2k Golang : Get constant name from value
+5.2k Javascript : How to loop over and parse JSON data?
+9.9k Golang : How to tokenize source code with text/scanner package?
+22.9k Golang : Print out struct values in string format
+9.2k Golang : How to extract video or image files from html source code
+9.1k Golang : Play .WAV file from command line
+6.5k Golang : Find the longest line of text example
+18.4k Golang : Display list of time zones with GMT
+8.6k Golang : GMail API create and send draft with simple upload attachment example
+4.4k Javascript : Access JSON data example