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
+12.6k Golang : Remove or trim extra comma from CSV
+16k Golang : How to reverse elements order in map ?
+14k Javascript : Prompt confirmation before exit
+7.8k Golang : Load DSA public key from file example
+10.2k Golang : Wait and sync.WaitGroup example
+4.9k Python : Find out the variable type and determine the type with simple test
+14.5k How to automatically restart your crashed Golang server
+14.3k Golang : How to convert a number to words
+7.5k Android Studio : AlertDialog to get user attention example
+9.6k Golang : How to generate Code 39 barcode?
+8.2k Prevent Write failed: Broken pipe problem during ssh session with screen command
+10.1k Golang : Text file editor (accept input from screen and save to file)