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.3k Golang : Rot13 and Rot5 algorithms example
+48.7k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+3.9k PHP : Extract part of a string starting from the middle
+17.1k Golang : Implement getters and setters
+7.8k Yum Error: no such table: packages
+12.3k Golang : Verify token from Google Authenticator App
+15.4k Golang : File path independent of Operating System
+28.2k Golang : Login(Authenticate) with Facebook example
+4.1k Golang : Constant and variable names in native language
+23.9k Golang : Convert uint value to string type
+6.3k Golang : File system scanning
+10.7k Golang : Split strings into command line arguments