我试图从类中保存一个Object。当我添加新记录(添加要保存的新对象)时,先前的记录将被删除。我究竟做错了什么?似乎一旦我添加了一个新对象,之前创建的对象就会因为idk而被删除。一直试着这几个小时。似乎无法弄明白。
void Department2File(HANDLE screen, Department &Departments, int deptcount)
{
Department Testing;
fstream file;
file.open("Departmentsdata.dat", ios::out | ios::binary);
file.close();
file.open("Departmentsdata.dat", ios::in | ios::out | ios::binary);
if (!file)
{
cout << "Error opening file.";
}
// writting data
long size = (deptcount * sizeof(Departments));
if (deptcount == 0)
{
size = (deptcount * sizeof(Departments));
}
else
{
size = (deptcount * sizeof(Departments))+1;
}
cout << "\nsaved!" << endl;;
file.clear();
file.seekp(size, ios::beg);
file.write(reinterpret_cast <char *>(&Departments), sizeof(Departments));
file.clear();
file.seekg(size, ios::beg);
file.read(reinterpret_cast<char *> (&Testing), sizeof(Departments));
cout << Testing.DepartmentID;////////////<--------------delete
///////////////////////////////
///////////////DELETE//////////
file.clear();
file.seekg(0, ios::beg);
file.get(reinterpret_cast<char *> (&Testing), sizeof(Departments));
cout <<"\n RECORD 0: "<<Testing.DepartmentID;
////////////////////////////
file.close();
}
答案 0 :(得分:0)
在ios::app
函数中添加标记open
,以在文件末尾添加输出:
file.open("Departmentsdata.dat", ios::out | ios::app | ios::binary);
点击此链接:http://www.cplusplus.com/doc/tutorial/files/
更新:尝试在代码中只使用一个:
fstream file;
file.open("Departmentsdata.dat", ios::out | ios::binary);
file.close();
file.open("Departmentsdata.dat", ios::in | ios::out | ios::binary);
像这样:
fstream file;
file.open("Departmentsdata.dat", ios::in | ios::app | ios::out | ios::binary);
//Write Something
file.close();
但这取决于你想要做什么。