Thursday, May 16, 2013

File Handling – C++ [ I ]



Simple Data File  - Reading and Writing

Data files are the file which store the data and a program require to write to a file and read from it.


Example :

 #include <iostream.h>

  class Files
      {
           private:
              char name[20];
              int sal;
           public:
              void FileWrite();
              void FileRead();
      };
  void Files::FileWrite()
      {
           ofstream fptr;
           char ch='y';
           fptr.open("Emp.txt");
           while(ch=='y')
              {
                   cout<<"\n\tEnter Name : ";
                   cin>>name;
                   cout<<"\n\tEnter Salary : ";
                   cin>>sal;
                   fptr<<name<<"  "<<sal<<"\n";
                   cout<<"\n\tWant to continue(y/n)? ";
                   cin>>ch;
              }
           fptr.close();
      }
  void Files::FileRead()
      {
           ifstream fptr;
           char name[20];
           int sal;
           fptr.open("Emp.txt");
           while(!fptr.eof())
              {
                   fptr>>name;
                   fptr>>sal;
                   cout<<name<<"  "<<sal<<"\n";
              }
           fptr.close();
      }

  int main()
      {
           Files F;
           int c=0;
           while(c!=3)
              {
                   cout<<"\n\n\t1. Write\n\t2. Read\n\t3. Exit";
                   cout<<"\n\n\t\tChoice? ";
                   cin>>c;
                   switch(c)
                        {
                            case 1:F.FileWrite();break;
                            case 2:F.FileRead();break;
                            case 3:break;
                        }
              }
      }

No comments: