C++/c++ and files
Expert: Prince M. Premnath - 7/29/2007
Questioni am a +2 student.need a c++ project.aprogramme including class and data files.pls take concern.thanks very much
AnswerHi dear jisha !
Your question is not too specific , you are looking for a project but you didn't specify the objective of your project !
Before using files in your c++ programs you should have some basic knowledge about the files , different types of file opening modes etc ,
Here im presenting a simple C++ program that uses files and classes hope you will get some ideas over file
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
class record
{
private:
char name[25];
int age;
friend class sample;
}rec;
class sample
{
private:
fstream iofile;
public :
sample();
void readinput();
void disp();
};
sample :: sample()
{ // open file in I/O mode
iofile.open("default.txt" , ios::in | ios::out);
if(!iofile)
{
cerr<<"Error opening file :";
exit(0);
}
}
void sample :: disp()
{
// Place the get pointer at the beginning of file
iofile.seekg(ios::beg);
while(iofile.read((char*)&rec , sizeof(rec)))
{
cout<<"Empl Name : " <<rec.name;
cout<<endl<<"Emp age :"<<rec.age<<endl;
}
}
void sample :: readinput()
{
char opt = 1;
do
{
cout<<"Enter employee name :";
cin>>rec.name;
cout<<"Enter age :";
cin>>rec.age;
// write data's
iofile.write((char*) &rec , sizeof(rec));
cout<<" Wish to add another rec <y/n>?:";
cin>>opt;
}while( opt != 'n');
}
void main()
{
sample a;
a.readinput();
a.disp();
}
Feel free to ask follow up if you have any detailed discussions over files !
Thanks and Regards
Prince M. Premnath