-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
101 lines (82 loc) · 1.92 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"flag"
"fmt"
"huffmanCompression/huffman"
"log"
"os"
"path/filepath"
"strings"
)
var programName = filepath.Base(os.Args[0])
func main() {
var help bool
compress := flag.Bool("c", false, "Specify a file to compress")
decompress := flag.Bool("d", false, "Specify a file to decompress")
flag.BoolVar(&help, "h", false, "Usage")
flag.BoolVar(&help, "help", false, "Usage")
flag.Parse()
if help {
usage()
os.Exit(0)
}
if *compress == false && *decompress == false {
usage()
os.Exit(1)
}
if *compress && *decompress {
log.Fatal("You can choose either compress or decompress. Try '--help' for more information.")
}
if len(flag.Args()) != 1 {
log.Fatal("Please provide a file. Try '--help' for more information.")
}
if *compress {
file := openFile(flag.Args()[0])
defer func(file *os.File) {
err := file.Close()
if err != nil {
log.Println(err)
}
}(file)
// add the .hf extension
outputPath := filepath.Base(file.Name()) + ".hf"
err := huffman.Encode(file, outputPath)
if err != nil {
log.Fatal(err)
}
} else if *decompress {
file := openFile(flag.Args()[0])
defer func(file *os.File) {
err := file.Close()
if err != nil {
log.Println(err)
}
}(file)
// remove the .hf extension
outputPath := strings.Split(filepath.Base(file.Name()), ".hf")[0]
err := huffman.Decode(file, outputPath)
if err != nil {
log.Fatal(err)
}
}
}
func usage() {
fmt.Printf(`
Usage: %s [OPTION] [FILE]
[OPTIONS]:
-c FILE ~file to compress
-d FILE ~file to decompress
[FILE]:
the file specified is the file to compress or decompress,
when compressed the file will be saved with a .hf extension,
when decompressed the file will be saved as a copy of the original file
`, programName)
}
func openFile(filename string) *os.File {
file, err := os.Open(filename)
log.Println("Opening file... ", filename)
if err != nil {
log.Fatal(err)
}
return file
}