Aim:
To implement file handling concept using random access
Algorithm:
- Start the process
- Get the input file called ExampleFile and check the file’s presence
- Seek the input file to a particular(random) location and get the specified output 4.Display the result
Program:
#include <iostream> #include<fstream> using namespace std; class person { protected: char name[80]; int age; public: void getData() { cout << "\n Enter name: "; cin >> name; cout << " Enter age: "; cin >> age; } void showData(void) { cout << "\n Name: " << name; cout << "\n Age: " << age; } }; int main() { char ch; person pers; fstream file; file.open("GROUP.DAT", ios::out | ios::in | ios::binary ); int chW; int i=10,count=0; while(i==10){ cout<<"\n\nMENU\n1.INSERT\n2.UPDATE\n3.DISPLA\n4.EXIT\n" ; cin>>chW; switch(chW) { case 1: { cout << "\nEnter person’s data:"; pers.getData(); file.seekp(count*sizeof(pers),ios::beg); file.write( reinterpret_cast<char*>(&pers), sizeof(pers) ); count++; } break; case 2: { file.seekp(0); int n; cout << "\nThere are " << count << " persons in file"; cout << "\nEnter person number: "; cin >> n; int position = (n-1) * sizeof(person); file.seekp(position); pers.getData(); file.write( reinterpret_cast<char*>(&pers), sizeof(pers) ); cout<<"PERSON "<<n<<" UPDATED"<<endl; } break; case 3: { file.seekg(0); int x=0; while( x<count ) { cout << "\nPerson:"<<x+1; file.read( reinterpret_cast<char*>(&pers), sizeof(pers) ); pers.showData(); x++; } cout << endl; } break; case 4: i=1; break; } } return 0; }
Execution:
INPUT : MENU 1.INSERT 2. UPDATE 3. DISPLAY 4. EXIT 1 AAA 20 1 BBB 19 3 2 1 CCC 53 3 4 OUTPUT : 1 Enter person’s data: Enter name: AAA Enter age: 20 MENU 1.INSERT 2.UPDATE 3.DISPLAY 4.EXIT 1 Enter person’s data: Enter name: BBB Enter age: 19 MENU 1.INSERT 2.UPDATE 3.DISPLAY 4.EXIT 3 Person:1 Name: AAA Age: 20 Person:2 Name: BBB Age: 19 MENU 1.INSERT 2.UPDATE 3.DISPLAY 4.EXIT 2 There are 2 persons in file Enter person number: 1 Enter name: CCC Enter age: 53 PERSON 1 UPDATED MENU 1.INSERT 2.UPDATE 3.DISPLAY 4.EXIT 3 Person:1 Name: CCC Age: 53 Person:2 Name: BBB Age: 19 MENU 1.INSERT 2.UPDATE 3.DISPLAY 4.EXIT 4
Result:
Thus, the implement a file handling concept using random access was executed successfully.