Reputation: 1
I am trying to populate a linked list after reading from a file. It simply hangs when i run it. I know the problem is associated with the assignment of &course (I may be wrong). Any guidance would be much appreciated.
Course course;//this one to read from file
Course* fileCourse = new Course();//this populates linked list
fstream Read("Courses.dat", ios::in | ios::binary);
if(!Read)
cout << "Error Reading from file Courses.dat\n" << endl;
else
{
Read.read(reinterpret_cast<char*>(&course), sizeof(Course));
fileCourse->setNextCourse(&course);//problem here perhaps?
while(Read && !Read.eof())
{
Read.read(reinterpret_cast<char*>(&course), sizeof(Course));
fileCourse->setNextCourse(&course);
if(head == NULL)
{
head = fileCourse;
}
else
{
Course* tmp = head;
tmp = tmp->getNextCourse();
while(tmp->getNextCourse() != NULL)
{
tmp = tmp->getNextCourse();
}
tmp->setNextCourse(fileCourse);
}
}
}
Upvotes: 0
Views: 418
Reputation: 437574
n
items (in this case, Course
objects) you should know that n
objects should be allocated with new Course()
. How many objects are you allocating in this code?Upvotes: 2
Reputation: 4839
If course is not POD (Plain Old Data) in taht it has member functions, pointers, etc embedded you may not be able to to write it byte for byte for a file and then read it in and expect to have a valid object. You need to serialize the data upon save and then deserialize it back to a valid object on load. This is sometimes done by overloading the stream operators << and >> to output/input the class to a file. Common data formats for serializing include XML or JSON, or even just binary data without any pointers.
The errors you are encountering are probably similar to what is being reported in this question: C++ Reading Objects from File Error
Upvotes: 0