温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

protobuf read/write multiple messages from/to a file

发布时间:2020-06-05 07:24:38 阅读:1069 作者:hakuyo 栏目:移动开发
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

由于在protobuf论坛上发过相关问题,但,根据https://developers.google.com/protocol-buffers/docs/techniques提供的相关解决办法,自己测试下想再反馈给论坛,下面是测试过的,当想放到论坛时,好像那个问题已经关闭了。

其实和自定义一种数据结构没什么区别。

proto file中的定义是:

enum FileAction {
   FILE_ACTION_ADD = 3;
   FILE_ACTION_DEL = 2;
   FILE_ACTION_MODIFY = 1;
   FILE_ACTION_RENAME = 0;
}

message FileState {
   required string name = 1;     // file name
   required FileAction state = 2;   // file state
}

#include "GFileState.pb.h" #include <fstream> #include <string> #include <iostream> using std::string; using std::fstream; using std::cout; int main(int argc,char* argv[]) {     string      fPath("message.txt");     string      strMsg;     char        buf[1024] = {0};     fstream     f;     int         size;     f.open(fPath.c_str(),std::ios_base::app | std::ios_base::binary);     FileState msg,msg2;     msg.set_name("D:\\Test1");     msg.set_state(FILE_ACTION_ADD);     msg.SerializeToString(&strMsg);     //msg.SerializePartialToString(&strMsg);     size        = strMsg.length();     f.write((char*)&size,sizeof(size));     f.write(strMsg.c_str(),size);     f.seekg(std::ios_base::end);      msg.set_name("/usr/home/nc/download");     msg.set_state(FILE_ACTION_MODIFY);     msg.SerializeToString(&strMsg);          size        = strMsg.length();     f.write((char*)&size,sizeof(size));     f.write(strMsg.c_str(),size);     f.close();      f.open(fPath.c_str(),std::ios_base::in | std::ios_base::binary);     f.seekg(std::ios_base::beg);     strMsg.clear();     size = 0;     while(!f.eof())     {            f.read((char*)&size,sizeof(size));         if(size > 0 && size < sizeof(buf))         {             f.read(buf,size);             msg.ParseFromString(buf);             cout<<"name:\t\t"<<msg.name()<<std::endl;             cout<<"state:\t\t"<<static_cast<int>(msg.state())<<std::endl;         }         msg.Clear();         memset(buf,'\0',sizeof(buf));         size = 0;     }     f.close();     std::cin >>strMsg;     return 0; } 

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×