Page 283 - DCAP404 _Object Oriented Programming
P. 283
Object-oriented Programming
Notes 2. The term ………………………. have been used with respect to the program.
3. The class ifstream has a member function ………………… that returns a nonzero value if
the end of the file has been reached.
4. The character read in the variable …………… is streamed to the standard output device
designated by cout.
5. Member function of the ………………….. 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.
13.2 Opening a File
The example programs listed above are indeed very simple. A data file can be opened in a
program in many ways. These methods are described below.
ifstream filename(“filename <with path>”); Or ofstream filename(“filename <with path>”);
This is the form of opening an input file stream and attaching the file “filename with path” in
one single step. This statement accomplishes a number of actions in one go:
1. Creates an input or output file stream
2. Looks for the specified file in the file system
3. Attaches the file to the stream if the specified file is found otherwise returns a NULL value
In case the file has been successfully attached to the stream the pointer is placed at the first
position The file stream created is accessible using the object’s name. The specified file is searched
in the specified directory if a path is included otherwise the file is searched only in the current
directory. If the file is not found it is created in case it is being opened for output. While opening
a file for output if the specified file is found then it is truncated before opening thereby loosing
all there was in the file before. Care should be taken to ensure that the program does not
overwrite a file unintentionally. In any case if the file is not found then a NULL value is returned
which we can check to ensure that we are not reading a file which was not found. This will cause
an error in the program if we attempt to read a file which was not found.
ifstream filename;
filename.open(“file name <with path>”);
In this approach the input stream - filename - is created but no specific file is attached to the
stream just created. Once the stream has been created a file can be attached to the stream using
open() member function of the class ifstream or ofstream as is exemplified by the following
program snippet which defines a function to read an input file.
#include <fstream.h>
void read(ifstream &ifstr) // file streams can be passed to functions
{
char ch;
while(!ifstr.eof())
{
ifstr.get(ch);
cout << ch;
}
276 LOVELY PROFESSIONAL UNIVERSITY