Friday, November 17, 2017

C++ File Operations on Binary Files

This C++ file management program will append data into a binary file.
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
class student
{
  int rollno;
  char name[20];
  char dept[10];

  public:
void getdata()
{
cout << "Rollno: ";
cin >> rollno;

cout << "Name: ";
cin >> name;

cout << "Branch: ";
cin >> dept;
}
};

int main()
{
  student s1;
  char ans='y';

  ofstream fout("student.txt", ios::app);

  while(ans=='y' || ans=='Y')
  {
s1.getdata();
fout.write((char *)&s1, sizeof(s1));
cout<<"Data appended in file successfully.\n";
cout<<"\nWant to add more data? (y/n)..";
cin>>ans;
  }

  fout.close();
  return 0;
}

Output of program:

Rollno: 101
Name: Amit
Branch: MCA
Data appended in file successfully.

Want to add more data? (y/n)..y
Rollno: 102
Name: Sunit
Branch: PhD
Data appended in file successfully.

Want to add more data? (y/n)..n

No comments:

Post a Comment