0% found this document useful (0 votes)
3 views18 pages

Oop CH5-1

This document covers file operations and the Standard Template Library (STL) in C++, detailing file handling methods, stream classes, and the use of templates for generic programming. It explains how to open, read, write, and close files using classes like fstream, ifstream, and ofstream, as well as the advantages of using templates for code reusability and flexibility. Additionally, it provides examples of function and class templates, including template specialization and generic functions for various data types.

Uploaded by

manthanmoondra0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

Oop CH5-1

This document covers file operations and the Standard Template Library (STL) in C++, detailing file handling methods, stream classes, and the use of templates for generic programming. It explains how to open, read, write, and close files using classes like fstream, ifstream, and ofstream, as well as the advantages of using templates for code reusability and flexibility. Additionally, it provides examples of function and class templates, including template specialization and generic functions for various data types.

Uploaded by

manthanmoondra0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Unit 5 :

File Operations and Standard Template


Library (STL)
Files are used to store data in a storage device permanently. File handling provides a
mechanism to store the output of a program in a file and to perform various
operations on it.

A stream is an abstraction that represents a device on which operations of input and


output are performed. A stream can be represented as a source or destination of
characters of indefinite length depending on its usage.

C++ Stream Classes and File operations


1. ios class is topmost class in the stream classes hierarchy. It is the base class
for istream, ostream, and streambuf class.

2. istream and ostream serves the base classes for iostream class. The class
istream is used for input and ostream for the output.

3. Class ios is indirectly inherited to iostream class using istream and


ostream. To avoid the duplicity of data and member functions of ios class,
it is declared as virtual base class when inheriting in istream and ostream

Opening and Closing a File


In C++ we have a set of file handling methods. These include ifstream, ofstream, and
fstream. These classes are derived from fstrembase and from the corresponding
iostream class. These classes, designed to manage the disk files, are declared in
fstream and therefore we must include fstream and therefore we must include this file
in any program that uses files.

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.

 ofstream: This Stream class signifies the output file stream and is applied to
create files for writing information to files
 ifstream: This Stream class signifies the input file stream and is applied for
reading information from files
 fstream: This Stream class can be used for both read and write from/to files.

All the above three classes are derived from fstreambase and from the corresponding
iostream class and they are designed specifically to manage disk files.

Modes of file handling


C++ provides us with the following operations in File Handling:

 Creating a file: open()


 Reading data: read()
 Writing new data: write()
 Closing a file: close()

Moving on with article on File Handling in C++

Opening a File
Generally, the first operation performed on an object of one of these classes is to
associate it to a real file. This procedure is known to open a file.

We can open a file using any one of the following methods:


1. First is bypassing the file name in constructor at the time of object creation.
2. Second is using the open() function.

To open a file use

1 open() function
Syntax

1 void open(const char* file_name,ios::openmode mode);

Here, the first argument of the open function defines the name and format of the file
with the address of the file.

The second argument represents the mode in which the file has to be opened.
Example
1 fstream new_file;
2 new_file.open(“newfile.txt”, ios::out);
In the above example, new_file is an object of type fstream, as we know fstream is a
class so we need to create an object of this class to use its member functions. So we
create new_file object and call open() function. Here we use out mode that allows us
to open the file to write in it.

Default Open Modes :

 ifstream ios::in
 ofstream ios::out
 fstream ios::in | ios::out

We can combine the different modes using or symbol | .

Example

ofstream new_file;

1 new_file.open(“new_file.txt”, ios::out | ios::app );


Here, input mode and append mode are combined which represents the file is
opened for writing and appending the outputs at the end.

As soon as the program terminates, the memory is erased and frees up the memory
allocated and closes the files which are opened.
But it is better to use the close() function to close the opened files after the use of the
file.

Using a stream insertion operator << we can write information to a file and using
stream extraction operator >> we can easily read information from a file.

Example of opening/creating a file using the open() function

#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file.close(); // Step 4: Closing file
}
return 0;
}
Output:

Explanation
In the above example we first create an object to class fstream and name it ‘new_file’.
Then we apply the open() function on our ‘new_file’ object. We give the name
‘new_file’ to the new file we wish to create and we set the mode to ‘out’ which allows
us to write in our file. We use a ‘if’ statement to find if the file already exists or not if
it does exist then it will going to print “File creation failed” or it will gonna create a
new file and print “New file created”.

Moving on with article on File Handling in C++

Writing to a File
Example:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file<<"Learning File handling"; //Writing to
file
new_file.close();
}
return 0;
}
Output:
Explanation

Here we first create a new file “new_file_write” using open() function since we wanted
to send output to the file so, we use ios::out. As given in the program, information
typed inside the quotes after Insertion Pointer “<<” got passed to the output file.

Moving on with this article on File Handling in C++

Reading from a File


Example

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::in);
if(!new_file)
cout<<"No such file"; } else { char ch; while
(!new_file.eof()) { new_file >>ch;
cout << ch;
}
new_file.close();
return 0;
}
Output:

Explanation

In this example, we read the file that generated id previous example i.e.
new_file_write.
To read a file we need to use ‘in’ mode with syntax ios::in. In the above example, we
print the content of the file using extraction operator >>. The output prints without
any space because we use only one character at a time, we need to use getline() with
a character array to print the whole line as it is.
Moving on with this article on File Handling in C++

Close a File
It is simply done with the help of close() function.

Syntax: File Pointer.close()

Example

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.txt",ios::out);
new_file.close();
return 0;
}
Output:

The file gets closed

C++ Templates
Templates can be represented in two ways:

o Function templates
o Class templates

A template is a simple yet very powerful tool in C++. The simple idea is to pass the 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 to sort() for different data types. Rather than writing
and maintaining multiple codes, we can write one sort() and pass the datatype as a parameter.
Using templates, it is possible to create generic functions and classes. In a generic function or
class, the type of data upon which the function or class operates is specified as a parameter.
Thus, you can use one function or class with several different types of data without having to
explicitly recode specific versions for each data type. Templates are sometimes called
parameterized classes or functions.

C++ adds two new keywords to support templates: ‘template’ and ‘type name’. The second
keyword can always be replaced by the keyword ‘class’.

The advantages of Generic Programming are


1. Code Reusability
2. Avoid Function Overloading
3. Once written it can be used for multiple times and cases.
How Do Templates Work?
Templates are expanded at compiler time. This is like macros. The difference is, that the
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 the same
function/class.

Function Template
● Generic functions use the concept of a function template. Generic functions define a set
of operations that can be applied to the various types of data.
● The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
● For example, Quick sorting algorithm is implemented using a generic function, it can be
implemented to an array of integers or array of floats.
● A Generic function is created by using the keyword template. The template defines what
function will do.

Syntax of Function Template


template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}
Where Ttype: It is a placeholder name for a data type used by the function. It is used within
the function definition. It is only a placeholder that the compiler will automatically replace this
placeholder with the actual data type.
class: A class keyword is used to specify a generic type in a template declaration.
Example: function that computes the maximum for three different integers

// C++ Program to demonstrate Use of template


#include <iostream>
using namespace std;

template <typename T> T myMax(T x, T y)


{
return (x > y) ? x : y;
}

int main()
{
// Call myMax for int
cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;

return 0;
}
Output
7
7
g

Example: WAP for swapping of two numbers using function template and display result
#include <iostream>
using namespace std;
template<class T> void swapValues(T &variable1, T &variable2)
{
T temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
int main()
{
int n1= 1, n2 = 2;
cout << “Original integer values are “<< n1 << “ “ << n2 << endl;
swapValues(n1, n2);
cout << “Swapped integer values are “ << n1 << “ “ << n2 << endl;
char c1 = ‘A’;
char c2 = ‘B’;
cout << "Original character values are: " << c1 << " " << cl2 << endl;
swapValues(c1, c2);
cout << "Swapped character values are: " << c1 << " " << c2;
return 0;
}
Example: Display value of passed variable using function template.
#include <iostream>
using namespace std;
template<class X> void display(X a,X b)
{
cout<<"\n Value of first variable="<<a;
cout<<"\n Value of second variable="<<b;
}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
display(i,j);
display(m,n);
return 0;
}
Output:
Value of first variable=2
Value of second variable=3
Value of first variable=2.3
Value of second variable=1.2

Example 3. This is a function template that prints the contents of the array
template<class T>
void printArray(const T*array, const int count)
{
for (int j = 0; j < count; j++)
cout << array[j] << “ “;
cout << endl;
}
This function will work on arrays of any class type when an appropriate insertion operator << has
been defined
int main()
{
const int aCount = 5;
const int bCount = 7;
const int cCount = 6;
int a[aCount] = {1, 2, 3, 4, 5};
double b[bCount] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7};
char c[cCount] = “HELLO”;
cout << “Array a contains: “ << endl;
printArray(a, aCount);
cout << “Array b contains: “ << endl;
printArray(b, bCount);
cout << “Array c contains: “ << endl;
printArray(c, cCount);
return 0;
}

Function Templates with Multiple Parameters


We can use more than one generic type in the template function by using the comma to separate
the list.

Syntax

template<class T1, class T2,.....>


return_type function_name (arguments of type T1, T2....)
{
// body of function.
}

Simple program:
#include <iostream>
using namespace std;
template <class type1, class type2>
void myfunc(type1 x, type2 y)
{
cout << x << ' ' << y << '\n';
}
int main()
{
myfunc(10, "I like C++");
myfunc(98.6, 19L);
return 0;
}
Using function template, we write code once and use it for any data type including user
defined
data types. For example, sort() can be written and used to sort any data type items. What if
we
want a different code for a particular data type? Is it possible to use different code only when
sort() is called for char data type?
It is possible in C++ to get a special behavior for a particular data type (here for char say for
example). This is called template specialization.
To denote the explicit specialization of a function, we need to mention that particular data
type
explicitly.
Syntax:
template < > ret-type func- name(specificdatatype parameter list)
{
// body of function
}
Example program for Function template specialization:
For example, consider the following simple code where we have general template fun() for
all
data types except int. For int, there is a specialized version of fun().
#include <iostream>
using namespace std;
template <class T> void fun(T a)
{
cout << "The main template fun(): " << a << endl;
}
template< > void fun(int a)
{
cout << "Specialized Template for int type: " << a << endl;
}
int main()
{
fun('a');
fun(10);
fun(10.14);
}
Output:
The main template fun(): a
Specialized Template for int type: 10
The main template fun(): 10.14

Experiment No 10 :
Exp 10 : 1. C++ program to find the sum of array elements using a function template:
#include <iostream>
using namespace std;

template <typename T>


T sum(T arr[], int n)
{
T total = 0;
for (int i = 0; i < n; i++) {
total=total+ arr[i];
}
return total;
}

int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "The sum of the elements of the array is: " << sum(arr, n) << endl;
return 0;
}

Exp 10-2 Write a C++ Program of Square Function using template specialization
● calculate the square of integer no. and a string. (Square of string is nothing
but Concatenation of a string with itself).

/* C++ Program of Square Function using template specialization */


#include <iostream>
using namespace std;
template <class T>
T square(T x)
{
T result;
result = x * x;
return result;
};

// template specialization
template <> string square<string>(string ss)
{
return (ss+ss);
};

int main()
{
int i = 2, ii;
string ww("Aaa");

ii = square<int>(i);
cout << i << ": " << ii << endl;

cout << square<string>(ww) << endl;


return 0;
}

OUTPUT:

2: 4
AaaAaa

Class Template:
Class Template can also be defined similarly to the Function Template. When a class uses the
concept of Template, then the class is known as generic class.
Class Templates like function templates, class templates are useful when a class defines
something that is independent of the data type.
The general form of a generic class declaration is shown here:
template <class X> class Classname
{
//body of class
};
Ttype is a placeholder name which will be determined when the class is instantiated. We can define
more than one generic data type using a comma-separated list. The Ttype can be used inside the class
body.
Instance: class_name<type> ob;

where class_name: It is the name of the class.


type: It is the type of the data that the class is operating on.
ob: It is the name of the object.

Example: Simple program to do addition of two numbers using Class Template:


#include <iostream>
using namespace std;
template<class T> class A
{
public:
T num1 = 5;
T num2 = 6;
void add()
{
cout << "Addition of num1 and num2 : " << num1+num2;
}

};

int main()
{
A <int> d;
d.add();
return 0;
}
Output:
Addition of num1 and num2 : 11
Class Template with multiple generic types:

We can use more than one generic data type in a class template, and each generic data type is
separated by the comma.
Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}

Simple program Class Template with multiple generic types :


#include <iostream>
using namespace std;
template<class T1, class T2>
class A
{
T1 a;
T2 b;
public:
A(T1 x,T2 y)
{
a = x;
b = y;
}
void display()
{
cout << "Values of a and b are : " << a<<" ,"<<b<<endl;
}
};

int main()
{
A<int,float> d(5,6.5);
d.display();
return 0;
}

Experiment No 10 :
c) C++ Program to build Simple calculator using Class template
#include <iostream>
using namespace std;

template <class T>


class Calculator
{
private:
T num1, num2;

public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}

void displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}

T add() { return num1 + num2; }

T subtract() { return num1 - num2; }

T multiply() { return num1 * num2; }

T divide() { return num1 / num2; }


};

int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);

cout << "Int results:" << endl;


intCalc.displayResult();

cout << endl << "Float results:" << endl;


floatCalc.displayResult();

return 0;
}

OUTPUT :
Int results:
Numbers are: 2 and 1.
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2

Float results:
Numbers are: 2.4 and 1.2.
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2

You might also like