这是我用来将列表一次导出到一个文件的方法:
#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();
}
说,我在列表中有3个对象(item1,item2,item3)。当我调用此方法时,cout将以正确的顺序显示列表的正确内容。但是当我查看输出文件/使用我的程序加载文件时,我将看到最后一个对象的3个重复项(item3,item3,item3)。我做错了什么?
答案 0 :(得分:3)
此行不生成Radio_Data
对象的正确地址:
file.write((char *)&listIter, sizeof(Radio_Data));
在获取对象的地址之前,您应该取消引用迭代器,如下所示:
file.write((char *)&(*listIter), sizeof(Radio_Data));
由于*listIter
求值为对迭代器指向的对象的引用,&(*listIter)
求值为指向相应Radio_Data
对象的指针。