Page 301 - DCAP404 _Object Oriented Programming
P. 301

Object-oriented Programming




                    Notes          are taken. The size parameter is an integer value that specifies the number of characters to be
                                   read or written from/to the memory block.


                                          Example:
                                   //  reading  a  complete  binary  file
                                   #include  <iostream>

                                   #include  <fstream>
                                   using  namespace  std;


                                   ifstream::pos_type  size;
                                   char  *  memblock;


                                   int  main  ()  {
                                       ifstream  file  (“example.bin”,  ios::in|ios::binary|ios::ate);
                                       if  (file.is_open())

                                     {
                                           size  =  file.tellg();
                                           memblock  =  new  char  [size];
                                           file.seekg  (0,  ios::beg);
                                           file.read  (memblock,  size);
                                           file.close();



                                           cout  <<  “the  complete  file  content  is  in  memory”;


                                           delete[]  memblock;
                                     }
                                       else  cout  <<  “Unable  to  open  file”;
                                       return  0;
                                   }      the  complete  file  content  is  in  memory
                                   In this example the entire file is read and stored in a memory block. Let’s examine how this is
                                   done:
                                   First, the file is open with the ios::ate flag, which means that the get pointer will be positioned
                                   at the end of the file. This way, when we call to member tellg(), we will directly obtain the size
                                   of the file. Notice the type we have used to declare variable size:
                                   ifstream::pos_type size;

                                   ifstream::pos_type is a specific type used for buffer and file positioning and is the type returned
                                   by file.tellg(). This type is defined as an integer type, therefore we can conduct on it the same
                                   operations we conduct on  any other integer value,  and can  safely be  converted to  another





          294                               LOVELY PROFESSIONAL UNIVERSITY
   296   297   298   299   300   301   302   303   304   305   306