I think I am writing incorrectly to my binary file. We are supposed to create a program that lets us add our college courses to a list with details like grade, units, etc. We're also supposed to double the array capacity whenever we add an item to our array (hence the function doubleArrayCapacity)
void doubleArrayCapacity(Course*&, int&, int);
...
int cap = 2;
int size = 0;
Course* courses = new Course[cap];
fstream fin;
fin.open("myCollegeCourses.9.bat", ios::binary|ios::in);
if (fin.good())
{
fin.read(reinterpret_cast<char*>(&size), sizeof(size));
doubleArrayCapacity(courses, cap, size);
fin.read(reinterpret_cast<char*>(courses), cap * sizeof(Course));
}
fin.close();
...
fstream fout;
fout.open("myCollegeCourses.9.bat", ios::binary|ios::out);
fout.write(reinterpret_cast<char*>(&size), sizeof(size));
fout.write(reinterpret_cast<char*>(courses), cap * sizeof(Course));
fout.close();
...
void doubleArrayCapacity(Course*& array, int& capacity, int newCapacity)
{
Course* temp = new Course[2 * capacity];
for (int i = 0; i < capacity; i++)
temp[i] = array[i];
delete [ ] array;
array = temp;
capacity = newCapacity * 2;
}
If I add 4 items to my array, the program works fine. Once I get to 5 objects, errors occur. The file is not read back correctly and the 5th item is read as null or zeros. I think I am not correctly outputting my data to my binary file. Can anyone see what I'm doing wrong?