Page 284 - DCAP404 _Object Oriented Programming
P. 284
Unit 13: Working with Files
cout << endl << “————” << endl; Notes
}
void main()
{
ifstream filename(“data1.dat”);
read(filename);
filename.close();
filename.open(“data2.dat”);
read(filename);
filename.close();
}
Notes Note how the same input file stream can be attached to different files at different
times.
ifstream filename(char *fname, int open_mode);
In this form the ifstream constructor takes two parameters - a filename and another the mode in
which the input file would be read. C++ offers a host of different opening modes for the input
file each offering different types of reading control over the opened file. The file opening modes
have been implemented in C++ as enumerated type called ios. The various file opening modes
are listed below.
Opening Mode Description
ios::in Open file in input mode for reading
ios::out Open file in output mode for writing
ios::app Open file in output mode for writing the new content at the end of the file
without removing the previous contents of the file.
ios::ate Open file in output mode for writing the new content at the current position of
the pointer without removing the previous contents of the file.
ios::trunc Open file in output mode for writing the new content at the beginning of the
file removing the previous contents of the file.
ios::nocreate The file is not created. The operation takes place on existing file. If the file is
not found an error occurs.
ios::noreplace The existing file is not overwritten. The operation takes place on existing file.
If the file is not found an error occurs.
ios::binary Opens the file in binary mode reading not a character but reading/writing
whatever binary value is stored in the file.
Note that all these values are int constants from an enumerated type ios. The following
program demonstrates the usages of a file opening mode.
#include <fstream.h>
void main()
{
LOVELY PROFESSIONAL UNIVERSITY 277