Question

This is the method I use to export a list to a file one object at once:

#define DATA_FILE "output.txt"
void File_Data::Save_Data(void)
{
    fstream file;
    remove(DATA_FILE);
    file.open(DATA_FILE, ios::out | ios::binary);
    file.seekg(ios::beg);
    for (listIter = listCont.begin(); listIter != listCont.end(); listIter++)
    {
        file.write((char *)&listIter, sizeof(Radio_Data));
        if (File_Error(file, "\nCan't update file\n"))
        {   return; }
        cout << "\nRecord " << listIter->GetName() << " added to file.\n" << endl;
        cout << "Name: " << listIter->GetName() << endl;
        cout << "Callsign: " << listIter->GetCallsign() << endl;
        cout << "Band: " << listIter->GetBand() << endl;
        cout << "Frequency: " << listIter->GetFrequency() << endl;
        cout << "Type: " << listIter->GetType() << endl;
        cout << "City: " << listIter->GetCity() << endl;
        cout << "Phone: " << listIter->GetPhone() << endl;
        cout << "Website: " << listIter->GetWebsite() << endl;
    }
    file.close();
}

Say, I have 3 objects in the list (item1, item2, item3). When I call this method, the cout will show the correct contents of the list in correct order. However when I look at the output file/load the file with my program, I will see 3 duplications of the last object (item3, item3, item3). What have I done wrong?

Was it helpful?

Solution

This line does not produce the correct address of your Radio_Data object:

file.write((char *)&listIter, sizeof(Radio_Data));

You should dereference the iterator before taking the address of the object, like this:

file.write((char *)&(*listIter), sizeof(Radio_Data));

Since *listIter evaluates to a reference to the object pointed to by the iterator, &(*listIter) evaluates to a pointer to the corresponding Radio_Data object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top