<p>下面是一个示例,用于在python中使用<code>protobuf 2.0</code>读取/写入对人类友好的文本文件。</p>
<pre><code>from google.protobuf import text_format
</code></pre>
<p>从文本文件中读取</p>
<pre><code>f = open('a.txt', 'r')
address_book = addressbook_pb2.AddressBook() # replace with your own message
text_format.Parse(f.read(), address_book)
f.close()
</code></pre>
<p>写入文本文件</p>
<pre><code>f = open('b.txt', 'w')
f.write(text_format.MessageToString(address_book))
f.close()
</code></pre>
<p><strong>c++</strong>等价物是:</p>
<pre><code>bool ReadProtoFromTextFile(const std::string filename, google::protobuf::Message* proto)
{
int fd = _open(filename.c_str(), O_RDONLY);
if (fd == -1)
return false;
google::protobuf::io::FileInputStream* input = new google::protobuf::io::FileInputStream(fd);
bool success = google::protobuf::TextFormat::Parse(input, proto);
delete input;
_close(fd);
return success;
}
bool WriteProtoToTextFile(const google::protobuf::Message& proto, const std::string filename)
{
int fd = _open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1)
return false;
google::protobuf::io::FileOutputStream* output = new google::protobuf::io::FileOutputStream(fd);
bool success = google::protobuf::TextFormat::Print(proto, output);
delete output;
_close(fd);
return success;
}
</code></pre>