Skip to content

Instantly share code, notes, and snippets.

@qfgaohao
Last active April 6, 2023 11:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qfgaohao/9bb9b3b75ceddd61f4f0450e3b74c350 to your computer and use it in GitHub Desktop.
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.
#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);
}
@SandSnip3r
Copy link

When opening a file for reading, ios::trunc does not make sense.

@qfgaohao
Copy link
Author

qfgaohao commented Apr 6, 2023

Thanks @SandSnip3r . You are right. It's an error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment