Binary Files - How To Read Data

This is the way i did it. but it isn't working. What is the error in my code. plz help
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Employee e;//object of class employee
fstream myfile;
myfile.open("Client_Details.dat",ios::in|ios::out|ios::binary);
myfile.seekg(0,ios::beg);

if(!myfile)
     cout<<"Can't Open The File"<<endl;

else
{
    while(!myfile.eof())
   {
        myfile.read(reinterpret_cast<char*>(&e),sizeof(Employee));
   }
//this is the //other code i used ,,,because this isn't working 
//while(myfile.read(char*)&e,sizeof(e))
//{
//   e.printEmployeeDetails();
//}
   
}
1. What do you mean "isn't working"?
2. Can we see the class definition of Employee (is Employee a plain-old-data class)?
3. How are you writing the Employees to the file?
Last edited on
if(!myfile)

Maybe you mean if (!myfile.is_open())?

if(!myfile) is the same as if(!myfile.good()). That condition will be true if any of the error flags have been set. In our case, if the file was not opened, then an error flag will be set so this is a valid check.
@ shacktar: Cool. So I guess that if I simply do if (myfile), the file stream gets converted to a void* which gets converted to bool?

http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/
Yes. There is an overloaded cast from stream (istream/ostream) to void*, wherein it simply returns 1 if good() and 0/NULL otherwise.
Last edited on
Topic archived. No new replies allowed.