[英]protocol buffers: how to serialize and deserialize multiple messages into a file (c++)?
[英]How to write multiple protocol buffers' messages into an a appendable compressed file?
我正在使用協議緩沖區的CodedOutputStream和FileOutputStream將多個消息按順序序列化為如下文件:
// File is opened using append mode and wrapped into
// a FileOutputStream and a CodedOutputStream
bool Open(const std::string& filename,
int buffer_size = kDefaultBufferSize) {
file_ = open(filename.c_str(),
O_WRONLY | O_APPEND | O_CREAT, // open mode
S_IREAD | S_IWRITE | S_IRGRP | S_IROTH | S_ISUID); //file permissions
if (file_ != -1) {
file_ostream_ = new FileOutputStream(file_, buffer_size);
ostream_ = new CodedOutputStream(file_ostream_);
return true;
} else {
return false;
}
}
// Code for append a new message
bool Serialize(const google::protobuf::Message& message) {
ostream_->WriteLittleEndian32(message.ByteSize());
return message.SerializeToCodedStream(ostream_);
}
// Code for reading a message using a FileInputStream
// wrapped into a CodedInputStream
bool Next(google::protobuf::Message *msg) {
google::protobuf::uint32 size;
bool has_next = istream_->ReadLittleEndian32(&size);
if(!has_next) {
return false;
} else {
CodedInputStream::Limit msgLimit = istream_->PushLimit(size);
if ( msg->ParseFromCodedStream(istream_) ) {
istream_->PopLimit(msgLimit);
return true;
}
return false;
}
}
如何使用GzipOutputStream執行相同的操作? 是否可以重新打開gzip壓縮文件以附加新消息,就像我使用CodedOutputStream一樣?
我剛剛意識到我只需要將FileOutputStream包裝在另一個GzipOutputStream中,如下所示:
file_ostream_ = new FileOutputStream(file_, buffer_size);
gzip_ostream_ = new GzipOutputStream(file_ostream_);
ostream_ = new CodedOutputStream(gzip_ostream_);
閱讀時,也要這樣做:
file_istream_ = new FileInputStream(file_, buffer_size);
gzip_istream_ = new GzipInputStream(file_istream_);
istream_ = new CodedInputStream(gzip_istream_);
關閉並重新打開文件以附加消息也可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.