Golang : Decompress zlib file example
Continuation from previous tutorial on how to zlib compress a file. In this part, we will learn how to decompress a file that was compressed with zlib compression algorithm.
Here are the codes :
package main
import (
"compress/zlib"
"flag"
"fmt"
"io"
"os"
"strings"
)
func main() {
flag.Parse() // get the arguments from command line
filename := flag.Arg(0)
if filename == "" {
fmt.Println("Usage : unzlib sourcefile.zlib")
os.Exit(1)
}
zlibfile, err := os.Open(filename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
reader, err := zlib.NewReader(zlibfile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer reader.Close()
newfilename := strings.TrimSuffix(filename, ".zlib")
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)
}
fmt.Println("Decompressed to ", newfilename)
}
Sample output :
./unzlib uncompressed.txt.zlib
Decompressed to uncompressed.txt
./unzlib
Usage : unzlib sourcefile.zlib
References :
http://golang.org/pkg/compress/zlib/
https://www.socketloop.com/tutorials/golang-zlib-compress-file-example
See also : Golang : zlib compress file example
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
+27.9k Golang : Move file to another directory
+19.2k Golang : Populate dropdown with html/template example
+50.9k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+7.9k Swift : Convert (cast) String to Float
+7.1k Nginx : How to block user agent ?
+15.6k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+12k Golang : Decompress zlib file example
+16.7k Golang : Get own process identifier
+8.7k Golang : Gorilla web tool kit schema example
+25.2k Golang : Get current file path of a file or executable
+10.4k Generate Random number with math/rand in Go