Gob 使用实例,将结构体写入文件里,在需要的时候再从文件中读取出来。

 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
package main

import (
        "bytes"
        "encoding/gob"
        "fmt"
        "io/ioutil"
        "os"
)

type Writer struct {
        Id    int
        Name  string
        Value string
}

type Reader struct {
        Name  string
        Value string
}

func writeToFile(filename string, data interface{}) bool {
        if len(filename) < 1 {
                fmt.Println("writeToFile filename invalid")
                return false
        }

        var w bytes.Buffer

        enc := gob.NewEncoder(&w)
        if err := enc.Encode(data); err != nil {
                fmt.Printf("Encode data error: %v\n", err)
                return false
        }

        if fp, err := os.Create(filename); err != nil {
                fmt.Printf("Open '%s' error: %v\n", filename, err)
                return false
        } else {
                defer fp.Close()
                fp.WriteString(w.String())
                fp.Sync()
        }

        return true
}

func readFromFile(filename string, data interface{}) {
        if len(filename) < 1 || data == nil {
                fmt.Println("readFromFile args invalid")
                return
        }

        contents, err := ioutil.ReadFile(filename)
        if err != nil {
                fmt.Printf("ReadFile '%s' error: %v\n", filename, err)
                return
        }

        r := bytes.NewBuffer(contents)
        dec := gob.NewDecoder(r)

        if err := dec.Decode(data); err != nil {
                fmt.Printf("Decode error: %v\n", err)
                return
        }

        return
}

func main() {
        wData := Writer{0, "firefox", "Web Broswer"}

        writeToFile("/tmp/w", &wData)

        rData := Reader{}
        readFromFile("/tmp/w", &rData)
        fmt.Printf("%v\n", rData)

        // test map
        w := map[string]string{
                "sublime-text": "Sublime Text",
                "firefox":      "Web Broswer",
                "terminator":   "Terminator",
        }
        writeToFile("/tmp/map", &w)
        r := make(map[string]string)
        readFromFile("/tmp/map", &r)
        fmt.Printf("%v\n", r)
}