the program runs successfully but the final output comes out in the form of an infinite loop...please help

#include<iostream.h>
#include<fstream.h>
#include<conio.h>
#include<stdio.h>
struct emp
{
 int eno;
 char name[20],desig[20];
 float sal;
}e;
void main()
{
clrscr();
ofstream f1;
f1.open("emp.dat",ios::app|ios::binary);
char ch='y';
while(f1)
{
 if(ch=='y'||ch=='Y')
 {
  cout<<"Enter the name"<<endl;
  gets(e.desig);
  cout<<"Enter the salary"<<endl;
  cin>>e.sal;
  cout<<"Enter the designation"<<endl;
  gets(e.desig);
  f1.write((char*)&e,sizeof(emp));
  cout<<"Do you want to enter more records??"<<endl;
  cin>>ch;
 }
 else
  f1.close();
}

ifstream f2;
f2.open("emp.txt",ios::binary);
cout<<"The File after appending is"<<endl;
f2.read((char*)&e,sizeof(emp));
while(!f2.eof())
{
 cout<<e.desig<<"  "<<e.name<<"  "<<e.sal;
 f2.read((char*)&e,sizeof(emp));
 f2.eof();
}
 f2.close();
getch();
}

also could you plz tell me the use of
f2.read((char*)&e,sizeof(emp));
f1.write((char*)&e,sizeof(emp));
our teacher didnt really explain its significance

This does not look like standard/modern c++. You should #include <iostream> instead of #include<iostream.h> Then you should do the reading with the >> ifstream operator instead of .read and the << ofstream operator instead of .write.

Dave

line 22: drop the gets() because its very buggy. In c++ programs you should be using cin.getline()

>>Then you should do the reading with the >> ifstream operator instead of .read and the << ofstream operator instead of .write

The file is a binary file, not a text file. So read() and write() are appropriate functions for binary files.

The last loop is incorrect. And use c++ cin.get() instead of getch()

while( f2.read((char*)&e,sizeof(emp)) )
{
 cout<<e.desig<<"  "<<e.name<<"  "<<e.sal << '\n';
}
f2.close();
cin.get();
}

Ah, didn't see that app|ios::binary.

but the final output comes out in the form of an infinite loop

Adding one thing...
you are writing to a file named "emp.dat" and then trying to open "emp.txt", which presumably does not exist (?). The bad usage of .eof() does not protect you from this. You can use .is_open() for checking whether a file was opened or not.
So, get rid of the .eof() there and read properly from the file the way Ancient Dragon showed. Naturally, pay attention to other suggestions too ;)

thnx evidently the prob was .dat and .txt extension prob.
the prog runs fine.
Thnx again

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.