Last active
April 6, 2023 11:05
-
-
Save qfgaohao/9bb9b3b75ceddd61f4f0450e3b74c350 to your computer and use it in GitHub Desktop.
Demonstrate how to save and read a protobuf message AddressBook to/from pb or pbtxt files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <string> | |
#include <sstream> | |
#include <google/protobuf/text_format.h> | |
// for read_from_pbtxt_nocopy | |
#include <fcntl.h> | |
#include <google/protobuf/io/zero_copy_stream_impl.h> | |
#include "addressbook.pb.h" | |
using namespace std; | |
using namespace tutorial; | |
bool save_to_pb(const AddressBook& address_book, string path) { | |
fstream fout(path, ios::out | ios::trunc | ios::binary); | |
if (!fout.is_open()) return false; | |
return address_book.SerializeToOstream(&fout); | |
} | |
bool read_from_pb(AddressBook& address_book, string path) { | |
fstream fin(path, ios::in | ios::trunc | ios::binary); | |
if (!fin.is_open()) return false; | |
return address_book.ParseFromIstream(&fin); | |
} | |
bool save_to_pbtxt(AddressBook& address_book, string path) { | |
string content; | |
if (google::protobuf::TextFormat::PrintToString(address_book, &content)) { | |
fstream out(path, ios::out | ios::trunc); | |
if (!out.is_open()) return false; | |
out << content; | |
out.close(); | |
return true; | |
} else { | |
return false; | |
} | |
} | |
bool read_from_pbtxt(AddressBook& address_book, string path) { | |
ifstream fin(path); | |
if (!fin.is_open()) return false; | |
stringstream ss; | |
ss << fin.rdbuf(); | |
return google::protobuf::TextFormat::ParseFromString(ss.str(), &address_book); | |
} | |
bool read_from_pbtxt_nocopy(AddressBook& address_book, string path) { | |
auto fd = open(path.c_str(), O_RDONLY); | |
if (fd < 0) { | |
return false; | |
} | |
google::protobuf::io::FileInputStream fin(fd); | |
fin.SetCloseOnDelete(true); | |
return google::protobuf::TextFormat::Parse(&fin, &address_book); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When opening a file for reading,
ios::trunc
does not make sense.