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
+34.1k Golang : Smarter Error Handling with strings.Contains()
+16.3k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+17.5k Golang : Simple client server example
+20.4k PHP : Convert(cast) int to double/float
+3.9k Javascript : Empty an array example
+30.5k Golang : Interpolating or substituting variables in string examples
+8.6k Golang : GMail API create and send draft with simple upload attachment example
+8.4k Golang : Set or add headers for many or different handlers
+20.8k Golang : Sort and reverse sort a slice of strings
+7.5k Golang : Scan files for certain pattern and rename part of the files
+10.2k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+12.1k Golang : Extract part of string with regular expression