Having issues reading in from a file

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();
}


No, EOF is only reached once you have gotten to the end of the file AND tried to read something. Loop like this instead:

while(IOFile)

Btw, the method you are using to save/load the classes will only work as long as your class doesn't contain any pointers, so be careful with it.
I tried changing the while loop to what you suggested, but the problem still occurs.

"People" is a struct..
1
2
3
4
5
6
struct Person
{
	static const int MAX = 16;
	char name[ MAX ];
	int age;
};
1
2
3
4
5
6
7
8
9
while(true)
{
    IOFile.read( ( char * ) &temp, sizeof( Person ) );
    
    //check for EOF immediately after reading
    if (!IOFile) break;
    
    cout << temp.name << " " << temp.age << endl;
}
Topic archived. No new replies allowed.