Page 281 - DCAP404 _Object Oriented Programming
P. 281
Object-oriented Programming
Notes filename << “This text will be saved in the file named cppio.dat in
C:\”;
filename.close();
return 0;
}
When you run this program the text This text will be saved in the file named cppio.dat in C:\
will be saved in a file named cppio.dat in the root directory of the C: drive. Let us run through
each line of this program.
#include <fstream.h>
C++ file stream classes and functions have been defined in this file. Therefore, you must include
this header file in the beginning of your C++ program so that these classes may be accessed.
ofstream filename (“c:\cppio.dat”);
This statement creates an object of class ofstream (acronym for output file stream) named filename.
This object acts as the output stream to write data in the specified file. Cppio.dat is the name of
the data file in which the program will write its output. If this file does not exists in the specified
directory, it is created there.
Notes Note that ofstream is a class. So, ofstream filename(“c:\cppio.dat”); creates an
object from this class.
Here the file name c:\cppio.dat is being passed to the constructor of this class. In short we create
an object from class ofstream, and we pass the name of the file we want to create, as an argument
to the class’ constructor. There are other things, too, that can be passed to the constructor.
filename << “This text will be saved in the file named cppio.dat in C:\”;
The << operator is a predefined operator. This line puts the text in the file. As mentioned before,
filename is a handle to the opened file stream. So, we write the handle name, << and after it we
write the text in inverted commas. If we want to pass variables instead of text in inverted
commas, just pass it as a regular use of the cout << as,
filename << variablename;
filename.close();
Having finished with writing into the file the stream must be closed. Filename is an object of
class ofstream, and this class has a function close() that closes the stream. Just write the name of
the stream object, dot and close(), in order to close the file stream. Note that once you close the
file, you can’t access it anymore, until you reopen it.
Before we take up the subject any further let us quickly go through a program that reads from a
data file and presents the same on the monitor. Here is the program listing.
#include <fstream.h>
void main() //the program starts here
{
ifstream filename(“c:\cppio.dat”);
char ch;
274 LOVELY PROFESSIONAL UNIVERSITY