Page 282 - DCAP404 _Object Oriented Programming
P. 282

Unit 13: Working with Files




                 while(!filename.eof())                                                         Notes
                 {
                         filename.get(ch);
                         cout  <<  ch;
                 }
                 filename.close();
          }
          Let us run through this program line by line quickly to catch some salient features.

          ifstream filename(“c:\cppio.dat”)

          Similar to ofstream, ifstream is the input stream for a file. The term input and output have been
          used with respect to the program. What goes to the program from outside is the input while
          processed data coming out of the program is the output. We here create an input file stream by
          the name - filename - to handle the input file stream. The parameter passed to the constructor is
          the file we wish to read into the program.

          char ch;

          This statement declares a variable of type char to hold one character at a time while reading
          from the file. In this program we intend to read one character at a time.

          while(!filename.eof())

          The class ifstream has a member function eof() that returns a nonzero value if the end of the file
          has been reached. This value indicates that there are no more characters in the file to be read
          further. This function is therefore used in the while loop for stopping condition. The file is read
          a character at a time till the last character has been successfully read into the program when the
          while loop  terminates.
          filename.get(ch);
          Another member function of the class ifstream is get() which returns the next character to be
          read from the stream followed by moving the character pointer to  the next character in the
          stream.
          cout <<  ch;


          The character read in the variable ch is streamed to the standard output device designated by
          cout (for console output, i.e., monitor) in this statement.

          filename.close();

          Since we reach at this statement when all the characters have been read and processed in the
          while loop, we are done with the file and hence it is duly closed.

          Self Assessment


          Fill in the blanks:
          1.   The data may be organized in ………………….. record or may be in free form text.



                                           LOVELY PROFESSIONAL UNIVERSITY                                   275
   277   278   279   280   281   282   283   284   285   286   287