Currently I'm working on a school assignment were I must build an application that can be used to make simple databases and store them on a file. The program has the options to add new records, display all records, search records and delete records.
So far I've been pleased with how easy file I/O is using C++'s stream classes, but I'm having a problem reading in data from the file and printing it.
Here's the code...
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void DisplayAllRecords()
{
Person temp;
IOFile.open( FILE_NAME, ios::binary | ios::in );
while( ! IOFile.eof() )
{
IOFile.read( ( char * ) &temp, sizeof( Person ) );
cout << temp.name << " " << temp.age << endl;
}
IOFile.close();
}
|
Only objects of type Person are written to the file.
The problem is the loop doesn't stop when I want it to, and it prints the last record in the file twice. So, say I had the two records..
name: aaa
age : 11
name: bbb
age : 22
The output from the previous function would be..
aaa 11
bbb 22
bbb 22
My thinking was once the second record is printed, the files get pointer would be at the end of the file, so the expression "! IOFile.eof() would evaluate to false.
Here's the function for writing to the file..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
void addRecord()
{
Person person;
IOFile.open( FILE_NAME, ios::binary | ios::app );
cout << "Enter name: ";
cin >> person.name;
cout << "Enter age: ";
cin >> person.age;
IOFile.write( ( const char * ) &person, sizeof( Person ) );
system( "cls" );
cout << "Record written to file";
IOFile.close();
}
|