Write a program to perform File Operation

/*
    File Operation
*/
#include<iostream>
#include<fstream>

using namespace std;

class Student
{
    int id;
    char name[20];

    public:
            void accept()
            {
                cout<<"\n\n Enter Name and Id: ";
                cin>>name>>id;
            }
            void display();
};

void Student::display()
{
    Student s;
   ifstream file("student.dat",ios::ate);
   cout<<"\n ID \t Name ";

    while(!file.eof())
    {
      cout<<endl<<id<<"\t"<<name;
      file.read((char*)&s,sizeof(s));
    }
}
int main()
{
    Student s;
    // Using Parameterized Constructor    //File opening mode
   // ofstream file("student.dat",ios::out); // Input Process


    // Another way

        ofstream file;
        file.open("student.dat");

    /*    by open member function
    */

    char ch;

    do
    {

        s.accept();
        //converting whole data in character Format
        file.write((char *)&s,sizeof(s) );
        cout<<"\n\n One row created: ";

        cout<<"\n\n Any more student[y/n]: ";
        cin>>ch;
    }while(ch=='y' || ch=='Y');

    s.display();
    file.close();

    return 0;
}

Previous
Next Post »