//program to insert data in a sorted file.....
#include<fstream.h>
#include<stdio.h>
#include<conio.h>
class stu
{
char name[20];
int marks;
public:
void getdata()
{ cout<<"name:";
cin>>name;
cout<<"marks:";
cin>>marks;
}
void putdata()
{ cout<<"\t name:"<<name
<<"\n marks:"<<marks<<endl;
}
int getmarks()
{return marks;}
}s1,stud;
void main()
{ clrscr();
ifstream fi("stu.dat",ios::in);
ofstream fo("temp.dat",ios::out);
char last ='y';
cout<<"enter details of student whose record is to be inserted\n";
s1.getdata();
while(!fi.eof())
{ fi.read((char*)&stud,sizeof(stud));
if(s1.getmarks()<=stud.getmarks())
{fo.write((char*)&s1,sizeof(s1)) ;
last='n';
break;
}
else
fo.write((char*)&stud,sizeof(stud));
}
if(last=='y')
fo.write((char*)&s1,sizeof(s1));
else if(!fi.eof())
{
while(!fi.eof())
{ fi.read((char*)&stud,sizeof(stud));
fo.write((char*)&stud,sizeof(stud));
}
}
fi.close();
fo.close();
remove("stu.dat");
rename("temp.dat","stu.dat");
fi.open("stu.dat",ios::in);
cout<<"file now contains\n";
while(!fi.eof())
{fi.read((char*)&stud,sizeof(stud));
if(fi.eof())
break;
stud.putdata();
}
fi.close();
getch();
}
Last edited on
You're using non-standard C++ from 15 years ago and even getting your code to compile requires rewriting.
If the input file does not open properly (for example, if it doesn't exist) this loop
else if(!fi.eof())
will loop forever.