Monday 6 May 2013

File Handling in C++


Introduction to stream
  • C++ still supports the entire C I/O system. However, C++ supplies a complete set of object oriented I/O routines.
  • To perform file I/O, you must include the header file fstream.h in your program.
  • It contains declaration of several classes, including ifstream, ofstream and fstream. These classes are derived from istream and ostream.

  • In C++, a file is opened by linking it to a stream. There are three types of streams: input, output, and input/output.
  • To create an input stream, declare an object of type ifstream. To create an output stream, declare an object of type ofstream.
  • To create an input/output stream, declare an object of type fstream.
  • Once you have created a stream, one way to associate it with a file is by using the function open()
About function open()

Prototype of function open is: open(const char *filename, openmode mode);

  • Here filename is the name of file, which can include a path specifier.
  • The value of mode determines how the file is opened. It must be a value of type openmode, which is an enumeration defined by ios that contains the following values:
    • ios::app
    • ios::ate
    • ios::binary
    • ios::in
    • ios::out
    • ios::trunc
  • You can combine two or more of these values by ORing them together.
  • Including ios::app causes all output to that file to be appended to the end. This value can be used only with files capable of output.
  • Including ios::ate causes a seek to the end of the file to occur when the file is opened. Although I/O operations can still occur anywhere with in the file.
  • The ios::in value specifies that the file is capable of input. The ios::out value specifies that the file is capable of output.
  • The ios::binary value causes a file to be opened in binary mode. By default, all files are opened in text mode.
  • The ios::trunc value causes the contents of a preexisting file by the same name to be destroyed and the file to be truncated to zero length

Text files

Text file streams are those where we do not include the ios::binary flag in their opening mode. These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.

Example:
#include<iostream>
#include<fstream>
#include<string>
#include<conio.h>
using namespace std;
int main()
{
     ofstream fout(“file.txt”);
fout<<”This is first line.\n”;
fout<<”This is second line.\n”;

fout.close();
string x;
ifstream fin(“file.txt”);
while(!fin.eof())
{
       getline(fin,x);
       cout<<x<<endl;
}
getch();
}

Output:

This is first line.
This is second line.
           



Reading and writing

To perform reading and writing you need to use member functions of one of the class from ifstream, ofstream or fstream.

Commonly used member function to read file content is read() and member function to write file content is write()

Example :
#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;
int menu()
{
    system("cls");
    cout<<"\n1. Read File";
    cout<<"\n2. Write File";
    cout<<"\n3. Exit";
    cout<<"\n\nEnter your choice";
    int ch;
    cin>>ch;
    return(ch);
}
void reading()
{
     ifstream fin("c:\\tc3\\file0.dat");
     char x;

     if(!fin)
             cout<<"File not found";
     else
     {
         while(fin>>x)
                 cout<<x;
        
     }
     fin.close();
}
void writing()
{
     ofstream fout("c:\\tc3\\file0.dat");
     char x;
     if(!fout)
             cout<<"File can not open";
     else
     {
         cout<<"Press Enter to Submit String"<<endl;
         do
         {
                          x=getche();
                          if(x==13)
                           break;
                          fout<<x;
                                                                         
         }while(1);
     }
     fout.close();
}
int main()
{
    int ch;
    while(1)
    {
           ch=menu();
           switch(ch)
           {
                     case 1:
                            reading();
                            break;                        
                     case 2:
                            writing();
                            break;
                     case 3:
                            exit(0);
                     default:
                            cout<<"Enter Valid choice";
           }
           getch();
    }
}  

Example :
#include<iostream>
#include<conio.h>
#include<fstream>
#include<iomanip>
using namespace std;
class Book
{
      int bookid;
      char title[30];
      float price;
      public:
             Book()
             { bookid=0; strcpy(title,""); price=0.0;}
             void getbook()
             {
                  cout<<"Enter Book ID: ";
                  cin>>bookid;
                  cout<<"Enter Book Title: ";
                  fflush(stdin);
                  gets(title);
                  cout<<"Price of Book: ";
                  cin>>price;
             }
             void showheader()
             {
                  cout<<left;
                  cout<<"\n"<<setw(10)<<"BOOK ID"<<setw(10)<<"Price"<<setw(10)<<"Title\n";
             }
             void showbook()
             {
                  cout<<left;
                  cout<<"\n"<<setw(10)<<bookid<<setw(10)<<price<<setw(10)<<title;
             }
             void reading();
             void writing();
};
int menu()
{
    system("cls");
    cout<<"\n1. Read File";
    cout<<"\n2. Write File";
    cout<<"\n3. Exit";
    cout<<"\n\nEnter your choice";
    int ch;
    cin>>ch;
    return(ch);
}
void Book:: reading()
{
     ifstream fin;
     char x;
     fin.open("c:\\tc3\\file1.dat",ios::in|ios::binary);
     if(!fin)
             cout<<"File not found";
     else
     {
         showheader();
         fin.read((char*)this,sizeof(*this));
         while(!fin.eof())
         {
                          fin.read((char*)this,sizeof(*this));
                          showbook();   
         }
     }
     fin.close();
}
void Book::writing()
{
     ofstream fout;
     char x;
     fout.open("c:\\tc3\\file1.dat",ios::out|ios::app|ios::binary);
     if(!fout)
             cout<<"File can not open";
     else
         fout.write((char*)this,sizeof(*this));       
    
     fout.close();
}
int main()
{
    Book b;
    int ch;
    while(1)
    {
           ch=menu();
           switch(ch)
           {
                     case 1:
                            b.reading();
                            break;                        
                     case 2:
                            b.getbook();
                            b.writing();
                            break;
                     case 3:
                            exit(0);
                     default:
                            cout<<"Enter Valid choice";
           }
           getch();
    }
}

No comments:

Post a Comment