温馨提示×

温馨提示×

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

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

protobuf read/write multiple messages from/to a file

发布时间:2020-06-05 07:24:38 来源:网络 阅读:1042 作者:hakuyo 栏目:移动开发

由于在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
}

  1. #include "GFileState.pb.h" 
  2. #include <fstream> 
  3. #include <string> 
  4. #include <iostream> 
  5. using std::string; 
  6. using std::fstream; 
  7. using std::cout; 
  8. int main(int argc,char* argv[]) 
  9.     string      fPath("message.txt"); 
  10.     string      strMsg; 
  11.     char        buf[1024] = {0}; 
  12.     fstream     f; 
  13.     int         size; 
  14.     f.open(fPath.c_str(),std::ios_base::app | std::ios_base::binary); 
  15.     FileState msg,msg2; 
  16.     msg.set_name("D:\\Test1"); 
  17.     msg.set_state(FILE_ACTION_ADD); 
  18.     msg.SerializeToString(&strMsg); 
  19.     //msg.SerializePartialToString(&strMsg); 
  20.     size        = strMsg.length(); 
  21.     f.write((char*)&size,sizeof(size)); 
  22.     f.write(strMsg.c_str(),size); 
  23.     f.seekg(std::ios_base::end); 
  24.  
  25.     msg.set_name("/usr/home/nc/download"); 
  26.     msg.set_state(FILE_ACTION_MODIFY); 
  27.     msg.SerializeToString(&strMsg); 
  28.      
  29.     size        = strMsg.length(); 
  30.     f.write((char*)&size,sizeof(size)); 
  31.     f.write(strMsg.c_str(),size); 
  32.     f.close(); 
  33.  
  34.     f.open(fPath.c_str(),std::ios_base::in | std::ios_base::binary); 
  35.     f.seekg(std::ios_base::beg); 
  36.     strMsg.clear(); 
  37.     size = 0; 
  38.     while(!f.eof()) 
  39.     {    
  40.         f.read((char*)&size,sizeof(size)); 
  41.         if(size > 0 && size < sizeof(buf)) 
  42.         { 
  43.             f.read(buf,size); 
  44.             msg.ParseFromString(buf); 
  45.             cout<<"name:\t\t"<<msg.name()<<std::endl; 
  46.             cout<<"state:\t\t"<<static_cast<int>(msg.state())<<std::endl; 
  47.         } 
  48.         msg.Clear(); 
  49.         memset(buf,'\0',sizeof(buf)); 
  50.         size = 0; 
  51.     } 
  52.     f.close(); 
  53.     std::cin >>strMsg; 
  54.     return 0; 

 

向AI问一下细节

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

AI