2012-12-07 12 views
6

私はこのようなファイルに順番に複数のメッセージをシリアル化するために、プロトコル・バッファー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を使用して同じことを行うことができますか? CodedOutputStreamを使用しているように、gzip圧縮ファイルを再オープンして新しいメッセージを追加できますか?

は、私はちょうど私はちょうどこのような別のGzipOutputStreamでのFileOutputStreamをラップする必要があることに気付きました

答えて

1

:、ちょうど

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_); 

閉じると再度開きますメッセージを追加するファイルも正常に動作します。

関連する問題