course* restoreList(course* head)//given by professor, should be right.
{
fstream fin;
fin.open("courses.dat", ios::binary|ios::in);
if(!fin)
{
cout<<"You don't have any course history yet. "<<endl;
return head;
}
// read the number of objects from the disk file
int nRecs;
fin.read((char*)&nRecs, sizeof(int));
cout<<"Reading Record: "<<nRecs<<endl;
// read the objects from the disk file
course* newHead = head; // the new listÂ
for (int i = 0; i< nRecs; i++)
{
course* c = new course;
fin.read((char*)c, sizeof(course));
newHead = push_back(c, newHead);
}
fin.close();
return newHead;
}
This is my writing file function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void saveList(course* head)
{
fstream fout;
fout.open("courses.dat", ios::binary|ios::out);
int nRecs;
course* p1;
for (nRecs=0, p1=head; p1; p1 = p1->next, nRecs++);
fout.write((char*)&nRecs, sizeof(int));
course* p;
for (p=head; p; p = p->next)
fout.write((char*)p, sizeof(course));
cout<<"RECORD: "<<nRecs<<endl;
fout.close();
return;
}
This is the class course:
1 2 3 4 5 6 7 8 9
class course
{
public:
char name[12];
char term[8];
int unit;
char grade;
course*next;
};
Problem is: my reading function can't read my output file. Can anyone see the problem is?