0% found this document useful (0 votes)
190 views8 pages

Templates and File Handling C++

The document discusses templates and file handling in C++. It provides examples of function templates, class templates, and how to create, read from, and write to files. Templates allow functions and classes to work with different data types by passing the type as a parameter. Files are used to permanently store data and the fstream library allows opening, reading, and writing files in C++. The lab tasks involve creating function and class templates, and reading/writing files.

Uploaded by

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

Templates and File Handling C++

The document discusses templates and file handling in C++. It provides examples of function templates, class templates, and how to create, read from, and write to files. Templates allow functions and classes to work with different data types by passing the type as a parameter. Files are used to permanently store data and the fstream library allows opening, reading, and writing files in C++. The lab tasks involve creating function and class templates, and reading/writing files.

Uploaded by

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

National University of Technology

Electrical Engineering Department

EE-1004: Introduction to Computer Programing Semester: IV

Lab 13: Templates and File handling in C++


Learning Objectives
 Familiarization with the generic properties of Templates.
 Understanding the concept of Function Templates and Class Templates
 Familiarization with the Opening, reading and writing to a file in c++.

Performance Lab Report

Description Total Marks Description Total Marks


Mark Obtain Mark Obtaine
s ed s d
Ability to 5 Organization/ 5
conduct an Structure
experiment
Implementation 5 Results 5
Total Marks obtained

Group:

Date of Experiment:

Instructor’s Signature:
Templates in C++
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 template works in a similar way as normal function, with slight difference. A single normal
function can only work with one set of data types, on the other hand a single function template can
work with different data types at once. In-case we need to perform identical operations on two or
more types of data, we use function overloading to create two functions with the required function
declaration.
Syntax
template <class T> or
template <typename T>

template <typename X>


X Function(X parameters)
{


}
Example
#include <iostream>
using namespace std;
  
// One function works for all data types.  This would work
// even for user defined types if operator '>' is overloaded
template <typename T>
T myMax(T x, T y)
{
   return (x > y)? x: y;
}
  
int main()
{
  cout << myMax<int>(3, 7) << endl;  // Call myMax for int
  cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double
  cout << myMax<char>('g', 'e') << endl;   // call myMax for char
  
  return 0;
}

Class templates
We also have the possibility to write class templates, so that a class can have members that
use template parameters as types. Like function templates, we can also create class
templates for generic class operations. Normally, you would need to create a different class
for each data type or create different member variables and functions within a single class.

Syntax
template <class T>
template <typename T>

class Class_Name
{
public:
T var;
T method(T arg);
};
Example
template <class T>
class mypair {
T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};

The class that we have just defined serves to store two elements of any valid type. For example, if we
wanted to declare an object of this class to store two integer values of type int with the values 115
and 36 we would write:

mypair<int> myobject (115, 36);


this same class would also be used to create an object to store any other type:
mypair<double> myfloats (3.0, 2.18);

The only member function in the previous class template has been defined inline within the class
declaration itself. In case that we define a function member outside the declaration of the class
template, we must always precede that definition with the template <...> prefix:

Example
template<Class T>
class Calculator
{
private: T a,b;
public:
Calculator(T x,T y)
{ a = x;
b = y;
}
T Add() { return a+b; }
T Sub () { return a-b; }
T Mul() { return a*b; }
T Div() { return a/b; }
};
int main()
{
Calculator<int> A(10,20);
Calculator<float> B(2.1,2.5);
cout<<A.Add();
Cout<<B.Add();
return 0;
}

Lab Task 1
Write a program to create a function template which calculates addition and subtraction between
 Two integers
 Two float values
 An integer and float value.

Lab Task 2
Write a program to create a class template to find greatest number between
 Three integers
 Three float values.
Files In C++
Files are named locations on disk to store related information. They are used to permanently store
data in a non-volatile memory (e.g. hard disk). Since Random Access Memory (RAM) is volatile
(which loses its data when the computer is turned off), we use files for future use of the data by
permanently storing them.

In C++, a file is categorized as either text or binary.Text files are structured as a sequence of lines
much like a string can be thought of as a sequence of characters.Each line is terminated with a
special character, called the EOL or End of Line character.

The fstream library allows us to work with files. To use the fstream library, include both the
standard <iostream> and the <fstream> header file:

Example
#include <iostream>
#include <fstream>

There are three classes included in the fstream library, which are used to create, write or read files

Class Description

ofstream Creates and writes to file

ifsteam Reads from files

fstream A combination of ofstream and ifstream: creates, reads, and


writes to files
Opening a File
Before performing any operation on a file, you must first open it. If you need to write to the file, open it
using fstream or ofstream objects. If you only need to read from the file, open it using the ifstream
object.
The three objects, that is, fstream, ofstream, and ifstream, have the open() function defined in them.
The function takes this syntax:
open (file_name, mode);
 The file_name parameter denotes the name of the file to open.
 The mode parameter is optional. It can take any of the following values:
Value Description
ios:: app The Append mode. The output sent to the file is appended to it.
ios::ate It opens the file for the output then moves the read and write control to file's end.
ios::in It opens the file for a read.
ios::out It opens the file for a write.
ios::trunk If a file exists, the file elements should be truncated prior to its opening.

Create and Write To a File


To create a file, use either the ofstream or fstream class, and specify the name of the file.To write to the file,
use the insertion operator (<<).

Example
#include <iostream>
#include <fstream>
using namespace std;

int main() {
  // Create and open a text file
  ofstream MyFile("filename.txt");

  // Write to the file


  MyFile << "Files can be tricky, but it is fun enough!";

  // Close the file


  MyFile.close();
}
Why do we close the file?
It is considered good practice, and it can clean up unnecessary memory space.

Read a File
To read from a file, use either the ifstream or fstream class, and the name of the file. Note that we
also use a while loop together with the getline() function (which belongs to the ifstream class) to read
the file line by line, and to print the content of the file:

Example

// Create a text string, which is used to output the text file


string myText;

// Read from the text file


ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
  // Output the text from the file
  cout << myText;
}

// Close the file


MyReadFile.close();

You might also like