oboerudata.go (1346B)
1 package main 2 import ( 3 "bufio" 4 "fmt" 5 "os" 6 "strings" 7 "strconv" 8 "time" 9 ) 10 11 func usage() { 12 fmt.Fprintf(os.Stderr, "usage: %s fifo\n", os.Args[0]) 13 } 14 15 func makemap(deck string) map[int]string { 16 f, err := os.OpenFile(deck + ".data", os.O_RDONLY, 0444) 17 defer f.Close() 18 if err != nil { 19 return nil 20 } 21 22 m := make(map[int]string) 23 r := bufio.NewScanner(f) 24 for r.Scan() { 25 str := strings.SplitN(r.Text(), "\t", 2) 26 key, _ := strconv.Atoi(str[0]) 27 m[key] = str[1] 28 } 29 return m; 30 } 31 32 func wait_and_print(fifo string) { 33 m := make(map[string]map[int]string) 34 for { 35 f, err := os.OpenFile(fifo, os.O_RDONLY, os.ModeNamedPipe) 36 if err != nil { 37 break 38 } 39 40 r := bufio.NewScanner(f) 41 r.Scan() 42 if r.Text() == "" { 43 f.Close() 44 break 45 } 46 47 var key int 48 var deck string 49 fmt.Sscanf(r.Text(), "%s\t%d", &deck, &key) 50 51 _, ok := m[deck] 52 if !ok { 53 split := strings.Split(deck, ".") 54 m[deck] = makemap(split[0]) 55 } 56 57 if m[deck] == nil { 58 fmt.Fprintln(os.Stderr, "Data for deck doesn't exist:", deck) 59 os.Exit(1) 60 } 61 62 str, ok := m[deck][key] 63 if !ok { 64 fmt.Fprintln(os.Stderr, "Data for card doesn't exist:", key) 65 os.Exit(1) 66 } 67 fmt.Fprintln(os.Stdout, str) 68 69 f.Close() 70 time.Sleep(50 * time.Millisecond) 71 } 72 } 73 74 func main() { 75 if len(os.Args) != 2 { 76 usage() 77 os.Exit(1) 78 } 79 80 fifo := os.Args[1] 81 82 wait_and_print(fifo) 83 }