最近学了一下protobuf,写了一个简单的例子,如下:
person.proto文件
- message Person{
- required string name = 1;
- required int32 age = 2;
- optional string email = 3;
- enum PhoneType{
- MOBILE = 1;
- HOME = 2;
- WORK = 3;
- }
- message Phone{
- required int32 id = 1;
- optional PhoneType type = 2 [default = HOME];
- }
- repeated string phoneNum = 4; //对应于cpp的vector
- }
写文件(write_person.cpp):
- #include <iostream>
- #include "person.pb.h"
- #include <fstream>
- #include <string>
- using namespace std;
- int main(){
- string buffer;
- Person person;
- person.set_name("chemical");
- person.set_age(29);
- person.set_email("ygliang2009@gmail.com");
- person.add_phonenum("abc");
- person.add_phonenum("def");
- fstream output("myfile",ios::out|ios::binary);
- person.SerializeToString(&buffer); //用这个方法,通常不用SerializeToOstream
- output.write(buffer.c_str(),buffer.size());
- return 0;
- }
读文件(read_person.cpp):
- #include <iostream>
- #include "person.pb.h"
- #include <fstream>
- #include <string>
- using namespace std;
- int main(){
- Person *person = new Person;
- char buffer[BUFSIZ];
- fstream input("myfile",ios::in|ios::binary);
- input.read(buffer,sizeof(Person));
- person->ParseFromString(buffer); //用这个方法,通常不用ParseFromString
- cout << person->name() << person->phonenum(0) << endl;
- return 0;
- }
- 顶