Not able to read more than one record in binary file

Hello, I'm not able to read binary file properly. Whenever I run the program it displays only the record which was entered at the last while entering data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void read()                                       
{
 fs.open("lib.dat", ios::in|ios::binary);
 ifstream   fin;
 fin.open("lib.dat", ios::binary | ios::ate);
 if(fin.tellg()==0)
 {
  cout<<"\n Database is empty! ";
  cout<<"Please add some entries.\n";
 }
 else
 {
  while(fs.read((char*)&l1, sizeof(l1)))
  {
   l1.display();
  }
 }
 fs.close();
}


In case you need to see program to enter data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void create()
{
 char ans;

 fs.open("lib.dat",ios::out|ios::binary);
 do
 {
  l1.getdata();
  fs.write((char*)&l1,sizeof(l1));
  cout<<"Enter more record? ";
  cout<<"Press 'Y' for yes "<<endl;
  cout<<"Press 'N' for no "<<endl;
  cin>>ans;
 }while(ans=='y' || ans=='Y');
 fs.close();
}


Thank you!
There isn't really enough code there to replicate exactly what is going on - I tried to run that code but had to invent a lot of extra code of my own. Nevertheless it seemed to work ok for me.

I'm always wary of code which uses global variables such as l1 and fs as there could be other parts of the program leaving them in an unexpected state, but I'm not sure that that would explain the problem.

Perhaps you need to post a minimal complete program which can be compiled and run in order to replicate the problem.
I'm not really confident what all to remove to make program short and also make sense hence, I'm linking pastebin link to whole code.

http://pastebin.com/7JBCNgN3

Thanks. I am able to compile that code, though it does have several features which are not part of modern standard C++. (Not tried to run it yet).

May I ask, out of interest which compiler (and version) you are using?
> I'm not really confident what all to remove to make program short
clrscr();
1
2
   cout<<"Press 1. to confirm."<<endl;
   cout<<"Press 0. to enter information again "; cin>>ans;
and other input validation are good canditates to remove.

Make `l1' and `fs' local to the function that use them.

Provide an example input.
Topic archived. No new replies allowed.