Click to See Complete Forum and Search --> : what wrong with mycode !! (about write read binary file)


nor1
January 7th, 2003, 09:06 AM
//writeread.cpp
#include <conio.h>
#include <fstream>
struct Person
{
char name[50];
int age;
char phone[24];
};
// Write a Person value to a file as binary
void write(ostream& out,Person value)
{
out.write(reinterpret_cast<char*>(&value),sizeof(value));
}
// Read a Person value from a file as binary
void read(istream& in,Person& value)
{
in.read(reinterpret_cast<char*>(&value),sizeof(value));
}
void writefile()
{
Person person1 = {"Robert", 28, "364-2534"};
Person person2 = {"Johny", 25, "208-1111"};
Person person3 = {"micheal", 30, "635-0066"};
ofstream outfile;
outfile.open("profile.dat", ios::out | ios::binary | ios::app);
write(outfile, person1);
write(outfile, person2);
write(outfile, person3);
outfile.close();
cout<<endl<<"write succeed !!";
getche();
}
void readfile()
{
Person profile;
ifstream inFile;
inFile.open("profile.dat", ios::bin | ios::in | ios::beg);
if(!inFile.fail())
{
int coutrec = 0;
while(!inFile.eof())
{
read(inFile,profile);
cout<<endl<<" Record : "<<++coutrec;
cout<<endl<<"name :"<<(profile.name); // name
cout<<endl<<"age :"<<(profile.age); // age
cout<<endl<<"phone :"<<(profile.phone); // phone number
}
}else
{ cout<<endl<<"open file fail!!!";
getche();
}
inFile.clear();
cout<<endl<<"end read file";
getche();
}
int main()
{
writefile();
readfile();
return 0;
}
/* output is
write succeed !!
Record : 1
name :Robert
age :28
phone :364-2534
Record : 2
name :Johny
age :25
phone :208-1111
Record : 3
name :micheal
age :30
phone :635-0066
Record : 4
name :micheal
age :30
phone :635-0066
end read file
*/

why it read 4 record ( record 3 and 4 is the same)
plese help me
thank you

Valen
January 7th, 2003, 10:29 AM
Do a primming read as follows:

read(inFile,profile);
while(!inFile.eof())
{
cout<<endl<<" Record : "<<++coutrec;
cout<<endl<<"name :"<<(profile.name); // name
cout<<endl<<"age :"<<(profile.age); // age
cout<<endl<<"phone :"<<(profile.phone); // phone number
read(inFile,profile);
}