1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
|
#include<iostream>
#include<fstream>
#include<cstdio>
using namespace std;
class Student
{
int admno;
char name[50];
public:
void setData()
{
cout << "\nEnter admission no. ";
cin >> admno;
cout << "Enter name of student ";
cin.getline(name,50);
}
void showData()
{
cout << "\nAdmission no. : " << admno;
cout << "\nStudent Name : " << name;
}
int retAdmno()
{
return admno;
}
};
/*
* function to write in a binary file.
*/
void write_record()
{
ofstream outFile;
outFile.open("student.dat", ios::binary | ios::app);
Student obj;
obj.setData();
outFile.write((char*)&obj, sizeof(obj));
outFile.close();
}
/*
* function to display records of file
*/
void display()
{
ifstream inFile;
inFile.open("student.dat", ios::binary);
Student obj;
while(inFile.read((char*)&obj, sizeof(obj)))
{
obj.showData();
}
inFile.close();
}
/*
* function to search and display from binary file
*/
void search(int n)
{
ifstream inFile;
inFile.open("student.dat", ios::binary);
Student obj;
while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() == n)
{
obj.showData();
}
}
inFile.close();
}
/*
* function to delete a record
*/
void delete_record(int n)
{
Student obj;
ifstream inFile;
inFile.open("student.dat", ios::binary);
ofstream outFile;
outFile.open("temp.dat", ios::out | ios::binary);
while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() != n)
{
outFile.write((char*)&obj, sizeof(obj));
}
}
inFile.close();
outFile.close();
remove("student.dat");
rename("temp.dat", "student.dat");
}
/*
* function to modify a record
*/
void modify_record(int n)
{
fstream file;
file.open("student.dat",ios::in | ios::out);
Student obj;
while(file.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() == n)
{
cout << "\nEnter the new details of student";
obj.setData();
int pos = -1 * sizeof(obj);
file.seekp(pos, ios::cur);
file.write((char*)&obj, sizeof(obj));
}
}
file.close();
}
int main()
{
//Store 4 records in file
for(int i = 1; i <= 4; i++)
write_record();
//Display all records
cout << "\nList of records";
display();
//Search record
cout << "\nSearch result";
search(100);
//Delete record
delete_record(100);
cout << "\nRecord Deleted";
//Modify record
cout << "\nModify Record 101 ";
modify_record(101);
return 0;
system("pause")
}
| |