From 07112012a19f2f8bfeac01830729f28862b16f1d Mon Sep 17 00:00:00 2001 From: Jian Han Date: Mon, 1 Jan 2018 22:07:44 +1000 Subject: [PATCH] compress files --- .../compressfiles/exampledata/example1.txt | 2 + .../compressfiles/exampledata/example2.txt | 1 + .../compressfiles/exampledata/example3.txt | 1 + .../compressfiles/exampledata/example4.txt | 1 + concurrency/compressfiles/main.go | 41 +++++++++++++++++++ 5 files changed, 46 insertions(+) create mode 100644 concurrency/compressfiles/exampledata/example1.txt create mode 100644 concurrency/compressfiles/exampledata/example2.txt create mode 100644 concurrency/compressfiles/exampledata/example3.txt create mode 100644 concurrency/compressfiles/exampledata/example4.txt create mode 100644 concurrency/compressfiles/main.go diff --git a/concurrency/compressfiles/exampledata/example1.txt b/concurrency/compressfiles/exampledata/example1.txt new file mode 100644 index 0000000..61f77c3 --- /dev/null +++ b/concurrency/compressfiles/exampledata/example1.txt @@ -0,0 +1,2 @@ + +example1 \ No newline at end of file diff --git a/concurrency/compressfiles/exampledata/example2.txt b/concurrency/compressfiles/exampledata/example2.txt new file mode 100644 index 0000000..b7d9bb0 --- /dev/null +++ b/concurrency/compressfiles/exampledata/example2.txt @@ -0,0 +1 @@ +example2 \ No newline at end of file diff --git a/concurrency/compressfiles/exampledata/example3.txt b/concurrency/compressfiles/exampledata/example3.txt new file mode 100644 index 0000000..eedfd49 --- /dev/null +++ b/concurrency/compressfiles/exampledata/example3.txt @@ -0,0 +1 @@ +example3 \ No newline at end of file diff --git a/concurrency/compressfiles/exampledata/example4.txt b/concurrency/compressfiles/exampledata/example4.txt new file mode 100644 index 0000000..2f7eee0 --- /dev/null +++ b/concurrency/compressfiles/exampledata/example4.txt @@ -0,0 +1 @@ +example4 \ No newline at end of file diff --git a/concurrency/compressfiles/main.go b/concurrency/compressfiles/main.go new file mode 100644 index 0000000..bdbd568 --- /dev/null +++ b/concurrency/compressfiles/main.go @@ -0,0 +1,41 @@ +package main + +import ( + "compress/gzip" + "fmt" + "io" + "os" + "sync" +) + +func main() { + var wg sync.WaitGroup + var i int = -1 + var file string + for i, file = range os.Args[1:] { + wg.Add(1) + go func(filename string) { + compress(filename) + wg.Done() + }(file) + } + wg.Wait() + fmt.Printf("Compressed %d files\n", i+1) +} +func compress(filename string) error { + // Unchanged from above + in, err := os.Open(filename) + if err != nil { + return err + } + defer in.Close() + out, err := os.Create(filename + ".gz") + if err != nil { + return err + } + defer out.Close() + gzout := gzip.NewWriter(out) + _, err = io.Copy(gzout, in) + gzout.Close() + return err +}