Operations on Files
* Opening the file
* Closing the file
* Data manipulations
Opening the file:
whenever we want to open a file we have to obtain a stream. There are three types of streams:
* input stream
* output stream
* Input/output stream
Note:
To create an input stream, we must declare the stream to be of type class ifstream.
To create an output stream, we must declare the stream to be of type class ofstream.
To create an input / output stream, we must declare the stream to be of type class fstream.
Once a stream has been created we have to associate a file with the stream. Then the file is available for processing.
Opening a file can be achieved in two ways.
* Using the constructor function of the stream class.
* Using the function open().
To open the file in output mode i.e. for creation:
In order to open a file in output mode, we have to use the object of the ofstream class.
Using constructor:
ofstream abc(“filename”);
where
ofstream : is an inbuilt class
abc: user defined object to open the file output mode
filename: user defined filename to store the data
example:
ofstream abc(“story.txt”)
ofstream abc(“student”)
Using function open:
ofstream abc;
abc.open(“filename”);
where
ofstream : is an inbuilt class
abc: user defined object to open the file output mode
filename: user defined filename to store the data
example:
ofstream abc;
abc.open(“story.txt”)
ofstream pqr;
pqr.open(“student”)
To open the file input mode i.e. for reading :
In order to open a file in input mode we have to use the object of the ifstream class.
Using constructor:
ifstream abc(“filename”);
where
ifstream : is an inbuilt class
abc: user defined object to open the file input mode i.e. for reading
filename: user defined filename to store the data
example:
ifstream abc(“story.txt”)
ifstream abc(“student”)
Using function open:
ifstream abc;
abc.open(“filename”);
where
ofstream : is an inbuilt class
abc: user defined object to open the file input mode i.e. for reading
filename: user defined filename to store the data
example:
ifstream abc;
abc.open(“story.txt”)
ifstream pqr;
pqr.open(“student”)
To open the file in input /output mode ie for reading and writing:
In order to open a file in input /output mode we have to use the object of the fstream class.
Using constructor:
fstream abc(“filename”,”filemode”);
where
fstream : is an inbuilt class
abc: user defined object to open the file for the specified mode.
filename: user defined filename to store the data
filemode: mode for which the file is to be opened(r,w,a).
example:
fstream abc(“story.txt”,”r”)
ifstream abc(“student”,”w”)
Using function open:
fstream abc;
abc.open(“filename”,”filemode”);
where
fstream : is an inbuilt class
abc: user defined object to open the file for the specified mode.
filename: user defined filename to store the data
filemode: mode for which the file is to be opened(r,w,a).
Example:
fstream abc;
abc.open(“story.txt”,”r”)
fstream pqr;
pqr.open(“student”,”w”)