C++ program for store student detail in a file:-
In this post i am going to write a C++ program that illustrate the use of file handling in C++. File handling requires when we want to save data for in future, if the data require then we can easily get them. Since, the life of a variables which we make in a program less than the life of the program. As soon as the program end the variables also vanished.
The following program construct a structure student containing the field for Roll no., Name, Class, Year and total marks.
The following program construct a structure student containing the field for Roll no., Name, Class, Year and total marks.
Let's begin the program:-
#include <iostream>
#include <fstream>
using namespace std;
struct student
{
int RollNo;
char Name[30];
int year;
char class1[30];
float total_marks;
};
void ReadStudent(student & TempStud)
{
cout << "\n Enter roll no.: ";
cin >> TempStud.RollNo;
cin.clear();
fflush(stdin);
cout << "\n Enter name: ";
cin.getline(TempStud.Name,30);
cout << "\n Enter class: ";
cin.clear();
fflush(stdin);
cin.getline(TempStud.class1,30);
cout << "\n Enter year";
cin>>TempStud.year;
cin.clear();
fflush(stdin);
cout<< "\n Enter total marks :";
cin>>TempStud.total_marks;
}
void WriteStudent(student TempStud)
{
cout << "\n The roll no.: ";
cout << TempStud.RollNo;
cout << "\n The name: ";
cout<< TempStud.Name;
cout<< TempStud.Name;
cout << "\n Class: ";
cout << TempStud.class1;
cout << "\n Year : ";
cout<< TempStud.year;
cout<< "\n Total marks: ";
cout<< TempStud.total_marks;
}
int main()
int main()
{
cout<<"\n 1. Enter data:";
cout<<"\n 2. Display data:";
cout<<"\n Enter your choice:";
short i;
cin>>i;
switch(i){
case 1:
{
struct student Student_Out;
ofstream StudFile_Out;
StudFile_Out.open("student.dat", ios::out | ios::binary | ios::trunc);
if(!StudFile_Out.is_open())
cout << "File cannot be opened \n";
char Continue = 'y';
do
{
ReadStudent(Student_Out);
StudFile_Out.write((char*) &Student_Out, sizeof(struct student));
if(StudFile_Out.fail())
cout << "File write failed";
cout << "Do you want to continue? (y/n): ";
cin >> Continue;
} while(Continue != 'n');
StudFile_Out.close();
break;
}
case 2:
{
struct student Student_In;
ifstream StudFile_In("student.dat", ios::in | ios::binary);
while(!StudFile_In.eof())
{
StudFile_In.read((char*) &Student_In, sizeof(struct student));
if(StudFile_In.fail())
break;
WriteStudent(Student_In);
}
StudFile_In.close();
break;
}
default:
cout<<"\n Invalid :";
main();
}
return 0;
}
Output:-
When user choice is 1:
When user choice is 2:
Comments
Post a Comment