I would suggest to use protobuf
Say you create following protobuf message, for example.
message binary_info
{
message struct_1
{
required int32 intValue = 1;
required string strValue = 2;
}
message struct_2
{
required int32 intValue = 1;
required uint64 ulongValue = 2;
}
message struct_3
{
required int32 intValue = 1;
required uint64 ulongValue = 2;
required string strValue = 3;
}
required struct_1 st1 = 1;
required struct_2 st2 = 2;
required struct_3 st3 = 3;
}
Let google protobuf create necessary files for you. See developer guide at https://developers.google.com/protocol-buffers/docs/overview
(In my example, protoc has auto generated message.pb.h and message.pb.cc files at communications/proto/*)
You can then write a program to save and read data to/from file
/*
* main.cpp
*
* Created on: 30/05/2014
* Author: ankit
*/
#include "communications/proto/message.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
bool write_data()
{
binary_info_struct_1* s1 = new binary_info_struct_1();
s1->set_intvalue(1);
s1->set_strvalue("string for s1");
binary_info_struct_2* s2 = new binary_info_struct_2();
s2->set_intvalue(2);
s2->set_ulongvalue(2000);
binary_info_struct_3* s3 = new binary_info_struct_3();
s3->set_intvalue(3);
s3->set_ulongvalue(3000);
s3->set_strvalue("string for s3");
binary_info b;
b.set_allocated_st1(s1);
b.set_allocated_st2(s2);
b.set_allocated_st3(s3);
if(!b.IsInitialized())
return false;
fstream output("myfile.data", ios::out | ios::binary);
b.SerializeToOstream(&output);
return true;
}
void read_data()
{
fstream input("myfile.data", ios::in | ios::binary);
binary_info b;
b.ParseFromIstream(&input);
cout << "struct 1, int data: " << b.st1().intvalue() << endl;
cout << "struct 1, string data: " << b.st1().strvalue() << endl;
cout << "struct 2, int data: " << b.st2().intvalue() << endl;
cout << "struct 2, ulong data: " << b.st2().ulongvalue() << endl;
cout << "struct 3, int data: " << b.st3().intvalue() << endl;
cout << "struct 3, ulong data: " << b.st3().ulongvalue() << endl;
cout << "struct 3, string data: " << b.st3().strvalue() << endl;
}
int main()
{
write_data();
read_data();
return 0;
}
Hope this helps!