Beruflich Dokumente
Kultur Dokumente
What is a File?
Files are the collection of related data stored in a particular area on the disk.
When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them
all.
However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C++.
You can easily move your data from one computer to another without any changes.
Types of Files
When dealing with files, there are two types of files you should know about:
Text files
Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using any simple
text editors such as Notepad.
When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least
security and takes bigger storage space.
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides better
security than text files.
Many real-life scenarios are there that handle a large number of data, and in such
situations, you need to use some secondary storage to store the data. The data are
stored in the secondary device using the concept of files. Programs can be written
to perform read and write operations on these files.
Working with files generally requires the following kinds of data communication
methodologies:
iostream standard library which provides cin and cout methods for reading from
standard input and writing to standard output respectively.
1. Ofstream: This file handling class in C++ signifies the output file stream and
is applied to create files for writing information to files
2. Ifstream: This file handling class in C++ signifies the input file stream and is
applied for reading information from files
3. Fstream: This file handling class in C++ signifies the file stream generally,
and has the capabilities for representing both ofstream and ifstream
All the above three classes are derived from fstreambase and from the
corresponding iostream class and they are designed specifically to manage disk
files.
Opening and Closing a File in C++
If programmers want to use a disk file for storing data, they need to decide about
the following things about the file and its intended use. These points that are to be
noted are:
Opening method
The first operation generally performed on an object of one of these classes to use a
file is the procedure known as to opening a file. An open file is represented within a
program by a stream and any input or output task performed on this stream will be
applied to the physical file associated with it. The syntax of opening a file in C++ is:
There are some mode flags used for file opening. These are:
ios::ate: open a file in this mode for output and read/write controlling to the
end of the file
ios::trunk: when any file already exists, its contents will be truncated before
file opening
When any C++ program terminates, it automatically flushes out all the streams
releases all the allocated memory and closes all the opened files. But it is good to
use the close() function to close the file related streams and it is a member of
ifsream, ofstream and fstream objects.
The structure of using this function is:
void close();
There are few important functions to be used with file streams like:
Syntax: filepointer.tellp()
Syntax: filepointer.tellg()
Note: For seekp and seekg three reference points are passed:
While doing C++ program, programmers write information to a file from the
program using the stream insertion operator (<<) and reads information using the
stream extraction operator (>>). The only difference is that for files programmers
need to use an ofstream or fstream object instead of the cout object and ifstream or
fstream object instead of the cin object.
Example:
#include <iostream.h>
#include <fstream.h>
void main () {
ofstream file;
file.open ("egone.txt");
file << "Writing to a file in C++....";
file.close();
getch();
}
#include <iostream.h>
#include<fstream.h>
void main()
{
char c,fn[10];
cout<<"Enter the file name....:";
cin>>fn;
ifstream in(fn);
if(!in)
{
cout<<"Error! File Does not Exist";
getch();
return;
}
cout<<endl<<endl;
while(in.eof()==0)
{
in.get(c);
cout<<c;
}
getch();
}
#include <iostream>
#include<fstream.h>
#include<math.h>
void main()
{
ofstream fileo("Filethree");
fileo<<"Hello GS";
fileo.close();
ifstream fin("Filethree");
char ch;
while(fin)
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
}
Templates in C++
Templates are used to prevent us from writing the same function or class
separately for different data types. We normally use templates in large programs
where we have to define the same function or class for different data types.
#include <iostream>
int sum( int x, int y)
{
return x + y;
}
float sum( float x, float y)
{
return x + y;
}
double sum( double x, double y)
{
return x + y;
}
int main()
{
cout << "Sum : " << sum(3, 5) << endl;
cout << "Sum : " << sum(3.0, 5.2) << endl;
cout << "Sum : " << sum(3.24234, 5.24144) << endl;
return 0;
}
Output
Sum : 8
Sum : 8.2
Sum : 8.48378
In this example, we defined a separate function to calculate the sum of three sets of
numbers, each with a different data type. Isn't it hectic to define the same function
again and again for different data types ?
This is where we need templates. There are two types of templates in C++.
Function Templates
Class Templates
Function Templates
T sum( T x, T y)
{
return x + y;
}
Compare this function template with the function in the previous example. You will
notice that this function template is the same as the function in the example,
except for the difference that here we have declared the parameter of type T instead
of int, float or double.
We need to tell the compiler that this is a function template because it will not
identify T ( since T is not a keyword ). For this, we need to include the following
code before including T as shown below.
#include <iostream>
template <typename T>
T sum( T x, T y)
{
return x + y;
}
int main()
{
cout << "Sum : " << sum(3, 5) << endl;
cout << "Sum : " << sum(3.0, 5.2) << endl;
cout << "Sum : " << sum(3.24234, 5.24144) << endl;
return 0;
}
Output
Sum : 8
Sum : 8.2
Sum : 8.48378
Here we declared a function template instead of writing three different functions for
each data type.
T sum( T x, T y) - This is the definition of the function template which is the same
as that of function. This tells us that both the parameters are of type T and the
return value is also of type T.
sum(3, 5) - Since both the arguments (3 and 5) are of type int, hence T will be of
type int. Thus, in this case, the function template becomes the function in the first
example.
Similarly, in the case of sum(3.0, 5.2), T becomes of type float and the template
becomes same as the second function in the first example. Same is in the third
case.
We can also write class keyword in place of typename keyword while declaring the
template parameter.
We can also write the following code by replacing the typename keyword by class
keyword.
In the above example, both the parameters of the function template were of the
same type. Hence we declared T for both. But what if the first parameter is of a
different type from the second?
Suppose we are multiplying an integer with a floating number and we have to
define a function for that. Then its one parameter will be of type int and another of
type float. In that case, we will define the function template with a different type for
each parameter as shown below.
T2 product( T1 x, T2 y)
return x * y;
Here we declared the function template with two types of template parameters T1
and T2, where T1 is the datatype of its first parameter which is an integer value
and T2 is of the second parameter which is a floating value. Since the product of an
int and a float is a float, hence its return type is also T2.
#include <iostream>
template < typename T1, typename T2 >
T2 product( T1 x, T2 y)
{
return (T2)(x * y);
}
int main()
{
cout << product(3, 4.7) << endl;
cout << product(4, 5.6) << endl;
return 0;
}
Output
14.1
22.4
Class Templates
We can create class templates just like function templates. To understand it, let's
take an example.
Consider two students in a class and we want to calculate the total marks of each
of them in two subjects. Suppose the marks of the first student in both the subjects
are integer values and that of the second student floating values.
#include <iostream>
template <class T>
class Student
{
T marks1;
T marks2;
public:
Student( T m1, T m2 )
{
marks1 = m1;
marks2 = m2;
}
T totalMarks()
{
return marks1 + marks2;
}
};
int main()
{
Student<int> s1 ( 45, 50 );
Student<float> s2 ( 47.5, 56.4 );
cout << "Total marks of student1 : " << s1.totalMarks() << endl;
cout << "Total marks of student2 : " << s2.totalMarks() << endl;
return 0;
}
Output
Total marks of student1 : 95