Serialise and deserialise vector in binary

前端 未结 4 1215
时光说笑
时光说笑 2020-12-11 21:42

I am having problems trying to serialise a vector (std::vector) into a binary format and then correctly deserialise it and be able to read the data. This is my first time us

4条回答
  •  感情败类
    2020-12-11 22:11

    I would write in network byte order to ensure file can be written&read on any platform. So:

    #include 
    #include 
    #include 
    #include 
    
    #include 
    
    int main(void) {
    
      std::vector v = std::vector();
      v.push_back(111);
      v.push_back(222);
      v.push_back(333);
    
    
      {
        std::ofstream ofs;
        ofs.open("vecdmp.bin", std::ios::out | std::ios::binary);
    
        uint32_t sz = htonl(v.size());
        ofs.write((const char*)&sz, sizeof(uint32_t));
        for (uint32_t i = 0, end_i = v.size(); i < end_i; ++i) {
          int32_t val = htonl(v[i]);
          ofs.write((const char*)&val, sizeof(int32_t));
        }
    
        ofs.close();
      }
    
      {
        std::ifstream ifs;
        ifs.open("vecdmp.bin", std::ios::in | std::ios::binary);
    
        uint32_t sz = 0;
        ifs.read((char*)&sz, sizeof(uint32_t));
        sz = ntohl(sz);
    
        for (uint32_t i = 0; i < sz; ++i) {
          int32_t val = 0;
          ifs.read((char*)&val, sizeof(int32_t));
          val = ntohl(val);
          std::cout << i << '=' << val << '\n';
        }
      }
    
      return 0;
    }
    

提交回复
热议问题