C++ Unit V
C++ Unit V
C++ Unit V
Unit V
Classes of file stream operations – Opening and Closing files – Detecting end of file
– More about open() function – File modes, File pointers and their manipulation – Sequential
input and output operations – Command-line arguments- Templates: class templates and
function templates.
we have been using the iostream standard library, which provides cin and cout methods for
reading from standard input and writing to standard output respectively.
1 Ofstream
This data type represents the output file stream and is used to create files and to write
information to files.
2 Ifstream
This data type represents the input file stream and is used to read information from files.
3 Fstream
This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files, and read
information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be included
in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And ifstream
object is used to open a file for reading purpose only.
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 1
Following is the standard syntax for open() function, which is a member of fstream,
ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the
second argument of the open() member function defines the mode in which the file should
be opened.
1 ios::app
Append mode. All output to that file to be appended to the end.
2 ios::ate
Open a file for output and move the read/write control to the end of the file.
3 ios::in
Open a file for reading.
4 ios::out
Open a file for writing.
5 ios::trunk
If the file already exists, its contents will be truncated before opening the file.
You can combine two or more of these values by ORing them together. For example if you
want to open a file in write mode and want to truncate it in case that already exists,
following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 2
Following is the standard syntax for close() function, which is a member of fstream,
ifstream, and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the
screen. The only difference is that you use an ofstream or fstream object instead of
the cout object.
int main () {
char data[100];
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 3
outfile << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
return 0;
}
When the above code is compiled and executed, it produces the following sample input and
output −
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline() function to
read the line from outside and ignore() function to ignore the extra characters left by
previous read statement.
C++ provides a special function, eof( ), that returns nonzero (meaning TRUE)
when there are no more data to be read from an input file stream, and zero
(meaning FALSE) otherwise.
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 4
1. Always test for the end-of-file condition before processing data
read from an input file stream.
a. use a priming input statement before starting the loop
b. repeat the input statement at the bottom of the loop body
2. Use a while loop for getting data from an input file
stream. A for loop is desirable only when you know the exact
number of data items in the file, which we do not know.
#include <iostream.h>
#include <fstream.h>
#include <assert.h>
int main(void)
{
int data; // file contains an undermined number of integer values
ifstream fin; // declare stream variable name
File Modes:
In C++, for every file operation, exists a specific file mode. These file modes allow us
to create, read, write, append or modify a file. The file modes are defined in the class ios.
Let's see all these different modes in which we could open a file on disk.
ios::in Searches for the file and opens it in the read mode only(if the file is
found).
ios::out
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 5
Searches for the file and opens it in the write mode. If the file is found,
its content is overwritten. If the file is not found, a new file is
created. Allows you to write to the file.
Searches for the file and opens it in the append mode i.e. this mode allows
ios::app
you to append new data to the end of a file. If the file is not found, a new
file is created.
"ios::binary" Searches for the file and opens the file(if the file is found) in a binary mode
to perform binary input/output file operations.
Searches for the file, opens it and positions the pointer at the end of the file.
ios::ate
This mode when used with ios::binary, ios::in and ios::out modes, allows
you to modify the content of a file.
"ios::trunc" Searches for the file and opens it to truncate or deletes all of its content(if
the file is found.
"ios::nocreate" Searches for the file and if the file is not found, a new file will not be
created.
File Pointer:
Every file maintains two pointers called get_pointer (in input mode file) and put_pointer (in
output mode file) which tells the current position in the file where reading or writing will
takes place. (A file pointer in this context is not like a C++ pointer but it works like a book-
mark in a book.). These pointers help attain random access in file. That means moving
directly to any location in the file instead of moving through it sequentially.
In C++, random access is achieved by manipulating seekg(), seekp(), tellg() and tellp()
functions. The seekg() and tellg() functions allow you to set and examine the get_pointer, and
the seekp() and tellp() functions perform these operations on the put_pointer.
The seekg() and tellg() functions are for input streams (ifstream) and seekp() and tellp()
functions are for output streams (ofstream). However, if you use them with an fstream object
then tellg() and tellp() return the same value. Also seekg() and seekp() work the same way in
an fstream object. The most common forms of these functions are :
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 6
ofstream & seekp(long);
seekp()
ofstream & seekp(long, seek_dir);
The seekg() or seekp(), when used according to Form 1, then it moves the get_pointer or
put_pointer to an absolute position. Here is an example:
ifstream fin;
ofstream fout;
: // file opening routine
fin.seekg(30); // will move the get_pointer (in ifstream) to byte number 30 in the file
fout.seekp(30); // will move the put_pointer (in ofstream) to byte number 30 in the file
When seekg() or seekp() function is used according to Form 2, then it moves the get_pointer
or put_pointer to a position relative to the current position, following the definition of
seek_dir. Since, seek_dir is an enumeration defined in the header file iostream.h, that has the
following values:
The file stream classes support a number of member functions for performing the input and
output operations on files. The functions get() and put() are capable of handling a single
character at a time. The function getline() lets you handle multiple characters at a time.
Another pair of functions i.e., read() and write() are capable of reading and writing blocks of
binary data.
The functions get() and put() are byte-oriented. That is, get() will read a byte of data and put()
will write a byte of data. The get() has many forms, but the most commonly used version is
shown here, along with put() :
The get() function reads a single character from the associated stream and puts that value in
ch. It returns a reference to the stream. The put() writes the value of ch to the stream and
returns a reference to the stream.
The following program displays the contents of a file on the screen. It uses the get() function :
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 7
/* C++ Sequential Input/Output Operations on Files */
#include<iostream.h>
#include<stdlib.h>
#include<fstream.h>
#include<conio.h>
void main()
{
char fname[20], ch;
ifstream fin; // create an input stream
clrscr();
Here is the sample output of the above C++ program. Let's suppose that the file contain the
following information:
#include <iostream>
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 9
cout << "You have entered " << argc
return 0;
Input:
$ g++ mainreturn.cpp -o main
$ ./main geeks for geeks
Output:
You have entered 4 arguments:
./main
geeks
for
geeks
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 10
Templates:
A template is a simple and yet very powerful tool in C++. The simple idea is to pass
data type as a parameter so that we don’t need to write the same code for different
data types. For example, a software company may need sort() for different data
types. Rather than writing and maintaining the multiple codes, we can write one
sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The
second keyword can always be replaced by keyword ‘class’.
How templates work?
Templates are expanded at compiler time. This is like macros. The difference is,
compiler does type checking before template expansion. The idea is simple, source
code contains only function/class, but compiled code may contain multiple copies of
same function/class.
Function Templates We write a generic function that can be used for different data
types. Examples of function templates are sort(), max(), min(), printArray().
Know more on Generics in C++
#include <iostream>
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 11
// One function works for all data types. This would work
T myMax(T x, T y)
int main()
cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double
cout << myMax<char>('g', 'e') << endl; // call myMax for char
return 0;
Output:
7
7
G
Class Templates
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 12
Like function templates, class templates are useful when a class defines something that is
independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack,
Queue, Array, etc.
Following is a simple example of template Array class.
#include <iostream>
class Array {
private:
T *ptr;
int size;
public:
void print();
};
size = s;
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 13
for(int i = 0; i < size; i++)
ptr[i] = arr[i];
void Array<T>::print() {
cout<<endl;
int main() {
a.print();
return 0;
Output:
12345
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 14