I am trying to write a data structure as such:
struct dataEntry
{
std::list<int> listTiles;
char* pData;
int nSize;
}
to a binary file.
I used ofstream to write to a binary file:
Write(char* fileName, const dataEntry& dataStruct)
{
ofstream binFile("fileName, ios::out | ios::binary | ios::trunc);
if(binFile.open())
{
binFile.write((char*)&dataStruct, sizeof(dataStruct));
binFile.close();
}
}
I used the same method to read back the binary file:
Read(char* fileName, const dataEntry& dataStruct)
{
ifstream binFile("fileName, ios::in| ios::binary );
if(binFile.open())
{
binFile.read((char*)&dataStruct, sizeof(dataStruct));
binFile.close();
}
}
However, i cannot iterate through the list after i read the binary file. It gave me an exception saying that the "list iterator outside range".
2nd problem is that when i tried to read the binary file the 2nd time, the "pData" is not what I have entered.
int Main()
{
char* name = "C:\\file.dat";
char* buf = "ABCDEFG";
dataEntry newData;
newData.listTiles.push_back(1);
newData.listTiles.push_back(2);
newData.nSize = 5;
newData.pData = buf;
Write(name, newData);
Read(name, newData);
buf = newData.pData; // wrong value when read 2nd time
newData.listTiles.remove(2); // crashed here
}
listobject. Google "object serialization".sizeof(dataStruct)never changes. you could have no items in the linked list, or a million items, thesizeof(dataStruct)stays the same. Again confirming that your method has no way of working correctly.0xa6718bee. How does that represent a string when you want to read it back? That certainly doesn't look like "ABCDEFG" to me.