Write a function template swap ( ) to swap two elements.
Q.5) a) Write a function template swap ( ) to swap two elements.
Ans.
#include < conio.h>
#include < iostream.h>
template< class T>
voidswapFunction(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
void main()
{
int i=100, j=200;
float x=20.1, y=40.3;
cout << "Original i, j: " << i << "\t" << j << endl;
cout << "Original x, y: " << x << "\t" << y << endl;
swapFunction(i, j); // swap integers
swapFunction(x, y); // swap floats
cout << "After Swapped integers i, j: " << i << "\t" << j << endl;
cout << "After Swapped float x, y: " << x << "\t" << y << endl;
}
Output:
Original i, j: 100 200
Original x, y: 20.1 40.3
After Swapped integers i, j: 200 100
After Swapped float x, y: 40.3 20.1
b.) Explain the role of seekg ( ), seekp ( ), tellg ( ) and tellp ( ) functions in the process of random access in a binary file.
Ans.
There are two file pointer are associated in each file.
Input Pointer or get pointer
Output Pointer or put pointer.
These two pointers are used while reading or writing the files. Get pointer is used while reading the content of file and put pointer is used for writing the content in the file. The input pointer is automatically set at the beginning of file if we open it in read-only mode. If we open a file in write-only mode, the available content of the file is deleted and the pointer is set at the starting point. If we open the file in the append mode, the output pointer is set to the end of the contents.
C++ provides different function for moving a file pointer to any other position in the file.
The following are the different functions that are provided by stream classes.
- seekg(): Sets the position of the get pointer.
Example:
finobj.seekg(0,ios::beg) -> It sets the pointer at the beginning.
finobj.seekg(n,ios::beg) -> Move forward by n byte from the current position.
finobj.seekg(n,ios::beg) -> Move backward by n byte from the current position
- seekp(): It moves output pointer to a specified location.
- tellg() : It gives the current position of the get pointer.
- tellp() : It gives the current position of the put pointer.
Example:
ofstream file;
file.open(“File_Name”,ios::app); // File open in append mode.
int total=file.tellp();
If you execute the above code, the file pointer moves at the end of contents and the variable total will represent the number of bytes in the file.