//---------------------------------- 簡單版
package main

import (
    "fmt"
    "encoding/gob"
    "os"
)

func main() {
    CreateFile()
    ReadFile()
    for{}
}

func ReadFile(){
    f, _ := os.Open("A.txt")
    enc := gob.NewDecoder(f)
    s := "" // 放入前物件與取出後物件需相同
    enc.Decode(&s)
    fmt.Println(s)

}

func CreateFile(){
    f, _ := os.Create("A.txt")
    enc := gob.NewEncoder(f)
    enc.Encode("AAA") // 可以放入其他物件 (如:Map)
    f.Close()
}



//------------------------------------------------ 進階版

package main

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

func savePats(file string, pats map[string]int) {
    f, err := os.Create(file)
    if err != nil {
        panic("cant open file")
    }
    defer f.Close()

    enc := gob.NewEncoder(f)
    if err := enc.Encode(pats); err != nil {
        panic("cant encode")
    }
}

func loadPats(file string) (pats map[string]int) {
    f, err := os.Open(file)
    if err != nil {
        panic("cant open file")
    }
    defer f.Close()

    enc := gob.NewDecoder(f)
        if err := enc.Decode(&pats); err != nil {
        panic("cant decode")
    }

    return pats
}

arrow
arrow
    全站熱搜

    黃彥霖 發表在 痞客邦 留言(0) 人氣()