检查存档是否是二进制/文本/xml

问题描述

我创建了一个输出 text_archive 并使用二进制存档恢复了它,显然,遇到了一些问题。 我能否以某种方式知道存档的类型,以便我可以使用适当的代码进行二进制/xml/文本存档。

class Info
{
private:
  // Allow serialization to access non-public data members.
  friend class boost::serialization::access;

  // Serialize the std::vector member of Info
  template<class Archive>
  void serialize(Archive & ar,const unsigned int version)
  {
    ar & filenames;
  }

  std::vector<std::string> filenames;


};


int main(int argc,char** argv)
{
  Info info;
  
   // Save filename data contained in Info object
  {
    // Create an output archive
    std::ofstream ofs( "store.dat" );
    **boost::archive::text_oarchive ar(ofs);**
    ar & info;
  }

  // Restore from saved data and print to verify contents
  Info restored_info;
  {
    // Create and input archive
    std::ifstream ifs( "store.dat" );
    **boost::archive::binary_iarchive ar(ifs);**
    // Load the data
    ar & restored_info;
  }
  return 0;
}

解决方法

你可以使用前两个字节来指定类型,比方说

00 表示二进制 01 为 xml 10 用于文本

内容的重置是为了数据本身