Here is my part of the code from binary file writing. here I'm passing a 2d vector table that contains text format data or binary data. if the main table contains binary data I wanna read and load that data into one vector table. I already done that if the data is text file I can load that data from that file, but it's a binary data I don't know how can I load. I am also using index table. That means that table contains size of the each field in main table.
For eg: emp.idx
field - Size
name - 20
age - 2
sex- 10
mainTbl - main table containing the binary data.
typedef vector <string> record_t;
typedef vector <record_t> table_t;
table_t mainTbl;
table_t fileStruct::FormatData(table_t &mainTbl)
{
fstream fs("emp.bin",ios::binary | ios::out | ios::in);
size_t rowLength=mainTbl.size();
size_t colLength=idxTbl.size();
count_t colSize;
for (size_t j=0;j<colLength;j++)
{
colSize.push_back(idxTbl[j].fsize);
//cout<<"colum size "<<colSize[j]<<endl;
}
for(size_t i=0;i<rowLength;i++)
{
for (size_t j=0;j<colLength;j++)
{
string data=mainTbl[i].at(j);
data.resize(colSize.at(j),' ');
mainTbl[i].at(j)=data;
int len = data.length();
fs.write(reinterpret_cast<char*> (&len),len);
fs.write(const_cast<char*>(data.c_str()),len);
//cout<<data;
//fu<<mainTbl[i].at(j);
}
fs<<endl;
//cout<<endl;
}
return mainTbl;
}
You made a mistake in your writing code
fs.write(reinterpret_cast<char*> (&len),len);
should be
fs.write(reinterpret_cast<char*>(&len), sizeof len);
To read you can read into a temporary vector and create the string from that.
vector<char> temp;
fs.read(reinterpret_cast<char*>(&len), sizeof len);
if (len > 0)
{
temp.resize(len);
fs.read(&temp[0], len);
}
mainTbl[i].at(j) = string(temp.begin(), temp.end());