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
+13.5k Golang : Linear algebra and matrix calculation example
+10.1k Golang : Convert octal value to string to deal with leading zero problem
+7k Mac/Linux/Windows : Get CPU information from command line
+26k Golang : Daemonizing a simple web server process example
+11k Golang : Removes punctuation or defined delimiter from the user's input
+8k Golang : Get today's weekday name and calculate target day distance example
+14.3k Golang : Fix image: unknown format error
+27.6k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+6.9k Golang : Get expvar(export variables) to work with multiplexer
+6.6k Golang : Handling image beyond OpenCV video capture boundary
+30.8k Golang : Remove characters from string example
+8.4k Swift : Convert (cast) Character to Integer?