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
|
$ pushd $GOPATH/src/protobuf-study
# 一个简单使用protobuf进行读写文件的例子
$ cat write.go
package main
import (
protobuf "github.com/golang/protobuf/proto"
"protobuf-study/goprotobuf"
"fmt"
"os"
)
func main() {
//初始化protobuf数据格式
msg := &goprotobuf.HelloWorld{
Id: protobuf.Int32(17),
Name: protobuf.String("BGbiao"),
Opt: protobuf.Int32(18),
}
filename := "./protobuf-test.txt"
fmt.Printf("使用protobuf创建文件 %s\n",filename)
fObj,_ := os.Create(filename)
defer fObj.Close()
buffer,_ := protobuf.Marshal(msg)
fObj.Write(buffer)
}
# 测试执行写文件程序
sh-4.2# go run write.go
使用protobuf创建文件 ./protobuf-test.txt
sh-4.2# cat -A protobuf-test.txt
^H^Q^R^FBGbiao^X^R
sh-4.2#
# 一个简单的通过之前定义的protobuf格式进行读取文件内容的例子
sh-4.2# cat read.go
package main
import (
protobuf "github.com/golang/protobuf/proto"
"protobuf-study/goprotobuf"
"fmt"
"io"
"os"
)
func checkError(err error) {
if err != nil {
fmt.Println(err.Error())
os.Exit(-1)
}
}
func main() {
filename := "protobuf-test.txt"
file,fileErr := os.Open(filename)
checkError(fileErr)
defer file.Close()
fs,fsErr := file.Stat()
checkError(fsErr)
buffer := make([]byte,fs.Size())
//把file文件内容读取到buffer
_,readErr := io.ReadFull(file,buffer)
checkError(readErr)
//初始化pb结构体对象并将buffer中的文件内容读取到pb结构体中
msg := &goprotobuf.HelloWorld{}
pbErr := protobuf.Unmarshal(buffer, msg)
checkError(pbErr)
fmt.Printf("读取文件:%s \r\nname:%s\nid:%d\nopt:%d\n",filename,msg.GetName(),msg.GetId(),msg.GetOpt())
}
sh-4.2# go run read.go
读取文件:protobuf-test.txt
name:BGbiao
id:17
opt:18
|