fnc.go (1271B)
1 package main 2 3 import ( 4 "encoding/csv" 5 "fmt" 6 "io" 7 "log" 8 "os" 9 "strconv" 10 ) 11 12 func usage() { 13 fmt.Fprintf(os.Stderr, "usage: %s [-d date] file\n", os.Args[0]); 14 os.Exit(1); 15 } 16 17 func main() { 18 var path, date string; 19 var n, loss, gain, total float64; 20 var arglen int; 21 var dflag bool; 22 23 arglen = len(os.Args); 24 if arglen - 1 == 0 { 25 usage(); 26 } 27 path = os.Args[arglen - 1]; 28 for i := 0; i < arglen; i++ { 29 if os.Args[i] == "-d" { 30 date = os.Args[i+1]; 31 dflag = true; 32 } else if os.Args[i] == "-h" { 33 usage(); 34 } 35 } 36 37 f, err := os.Open(path); 38 if err != nil { 39 log.Fatal(err); 40 } 41 defer f.Close(); 42 43 csvr := csv.NewReader(f); 44 if err != nil { 45 log.Fatal(err); 46 } 47 header, err := csvr.Read(); 48 if err != nil { 49 log.Fatal(err); 50 } 51 fmt.Println(header); 52 53 for { 54 line, err := csvr.Read(); 55 if err != nil { 56 if err == io.EOF { 57 break; 58 } 59 log.Fatal(err); 60 } 61 if dflag && date != line[0] { 62 continue; 63 } 64 n, err = strconv.ParseFloat(line[2], 64); 65 if err != nil { 66 log.Fatal(err); 67 } 68 if n >= 0 { 69 gain += n; 70 } else { 71 loss += n; 72 } 73 total += n; 74 fmt.Printf("%-15s %-20s %-.2f\n", line[0], line[1], n); 75 } 76 fmt.Println(); 77 fmt.Printf("Loss: %.2f\n", -loss); 78 fmt.Printf("Gain: %.2f\n", gain); 79 fmt.Printf("Total: %.2f\n", total); 80 }