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
+8.4k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+17.3k Golang : Padding data for encryption and un-padding data for decryption
+7.1k Golang : HTTP Server Example
+8.9k Golang : Edge detection with Sobel method
+9.9k Golang : Read until certain character to break for loop
+6.4k Golang : Example of how to detect which type of script a word belongs to
+18.1k Golang : How to run your code only once with sync.Once object
+9.1k Golang : Text file editor (accept input from screen and save to file)
+6.6k Gogland : Single File versus Go Application Run Configurations
+30.1k Golang : Math pow(the power of x^y) example
+3.8k JavaScript : Rounding number to decimal formats to display currency