Pages

Friday, June 29, 2018

Complete File I O program in C using Turbo C C compiler

Complete File I O program in C using Turbo C C compiler


#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<iomanip.h>

class student
{
private:
char name[20];
char address[50];
int roll;
float marks;

public:
void getdata()
{
cout<<"enter the name of the student:";cin>>name;
cout<<"enter the address of the student:";cin>>address;
cout<<"enter the roll no of the student:";cin>>roll;
cout<<"enter the marks of the student:";cin>>marks;
}

void putdata()
{

cout<<setw(10)<<name<<setw(15)
<<address<<setw(10)<<roll
<<setprecision(2)<<setw(10)
<<marks<<endl;
}
};



int main()
{
student std;
fstream inout;
inout.open("student.txt",ios::out|ios::in|ios::ate|ios::binary);
int m;
cout<<"What do you like to do?"<<" ";
cout<<"Enter 1 to write into file: ";
cout<<"Enter 2 to display the content of file:"<<" ";
cout<<"Enter 3 to update record in file:"<<" ";
cout<<"Enter 4 to display the appended file:"<<" ";
cout<<"Enter 5 to modify record of student:"<<" ";
cout<<"Enter 6 to count number of objects in file:";
cin>>m;
switch(m)
{
case 1:
{
inout.seekg(0,ios::beg);
int z;
cout<<"Enter the number of students";cin>>z;
for(int k=1;k<=z;k++)
{
std.getdata();
inout.write((char *)&std,sizeof(std));
}
break;
}
//Displays current contents
case 2:
{
cout<<"current contents of file"<<" ";
inout.seekg(0,ios::beg);

cout<<setw(10)<<"name"<<setw(15)
<<"Address"<<setw(10)<<"Roll"
<<setprecision(2)<<setw(10)
<<"Marks"<<endl;
while(inout.read((char *)&std,sizeof(std)))
{
std.putdata();
}
inout.clear();
break;
}

//update student record
case 3:
{
cout<<" Add a student ";
std.getdata();
char ch;
cin.get(ch);
inout.write((char *) &std,sizeof(std));
cout<<"Record Added";
break;
}


//Display the appended file,Note that this case block is same as case 2 block
case 4:
{
inout.seekg(0,ios::beg);

cout<<"Contents of the appended file ";
while(inout.read((char *) &std,sizeof(std)))
{
std.putdata();
}
inout.clear();
break;
}




//Modify Record
case 5:
{
cout<<"Enter the object number to be modified ";
int object;
cin>>object;
char ch;
cin.get(ch);
int location=(object-1)*sizeof(std);
if (inout.eof())
inout.clear();
inout.seekg(location);
cout<<"Enter The new data of the student ";
std.getdata();
cin.get(ch);
inout.write((char *)& std,sizeof(std))<<flush;
//show updated file
cout<<"Contents of the updated file ";
inout.seekg(0);
while(inout.read((char *)&std,sizeof(std)))
{
std.putdata();
}
inout.clear();
break;
}

//Find the number of the objects in the file
case 6:
{
int last=inout.tellg();
int n=last/sizeof(std);
cout<<"Number of objects="<<n<<" ";
cout<<"Total Bytes in the file="<<last<<" ";
break;
}
default:
{
cout<<" Wrong choice";
}
}//switch statement closed

inout.close(); //closing the file
getch();
return 100;
}


visit link download

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.