I'm having trouble when it comes to reading from a binary file within a function after writing to it in a previously used function. The function writes an instance of a class to a spot in the binary file determined by a member of the class, itemID.
The class and binary file variable are initialized here.
1 2 3
|
fstream fio;
Hardware ht;
init(ht, fio);
|
The initializing function begins to fill this temporary class, HT, and write it to FIO in a spot determined by the temporary class's item ID.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void init(Hardware ht, fstream& fio)
{
fstream fio("hardware.dat", ios::in | ios::out | ios::binary | ios::trunc);
int id, or ;
float ma, se;
char name[30];
fstream init("init.txt", ios::in);
while (!init.eof())
{
init >> id >> or >> ma >> se; init.getline(name, 20);
ht.init(id, or , ma, se, name);
fio.seekp(id);
fio.write((char*)(&ht), sizeof(ht));
}
|
Now, this seems to work fine. It seems to be writing properly. The problem comes from trying to open this in a later function to READ from. The information is flat out unreadable.
This is how the function is called in the main.
And this is the bulk of the function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
void check(Hardware ht, fstream& fio)
{
fio.open("hardware.dat");
if (!fio)
{
cout << "Can't open file";
_getch();
exit(1);
}
int in, i;
cout << "Enter an item ID. " << endl;
cin >> in;
for (i = 0; i < 200; i++)
{
fio.seekg(i);
fio.read((char*)(&ht), sizeof(ht));
if (ht.getID() == in)
{
ht.print();
}
}
|
What is it about my syntax with opening the file that makes it incomprehensible? The read temporary class is filled with who knows what after each run of the for loop.
In short, the binary file that is written to becomes unusable, and I don't know why.