Sie sind auf Seite 1von 12

WORKING WITH FILES

What is a File?

A file is a container in computer storage devices used for storing data.

Files are the collection of related data stored in a particular area on the disk.

Why files are needed?

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

Binary files are mostly the .bin files in your computer.

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:

 Data transfer between console units

 Data transfer between the program and the disk file

iostream standard library which provides cin and cout methods for reading from
standard input and writing to standard output respectively. 

File Handling Classes

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:

 A name for the file

 Data type and structure of the file


 Purpose (reading, writing data)

 Opening method

 Closing the file (after use)

Files can be opened in two ways. They are:

1. Using constructor function of the class

2. Using member function open of the class

Opening a file in C++

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:

open (filename, mode);

There are some mode flags used for file opening. These are:

 ios::app: append mode

 ios::ate: open a file in this mode for output and read/write controlling to the
end of the file

 ios::in: open file in this mode for reading

 ios::out: open file in this mode for writing

 ios::trunk: when any file already exists, its contents will be truncated before
file opening

Closing a file in C++

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();

General functions used for File handling

1. open(): To create a file

2. close(): To close an existing file

3. get(): to read a single character from the file

4. put(): to write a single character in the file

5. read(): to read data from a file

6. write(): to write data into a file

Special operations in a File

There are few important functions to be used with file streams like:

tellp() - It tells the current position of the put pointer.

Syntax: filepointer.tellp()

tellg() - It tells the current position of the get pointer.

Syntax: filepointer.tellg()

seekp() - It moves the put pointer to mentioned location.

Syntax: filepointer.seekp(no of bytes,reference mode)

seekg() - It moves get pointer(input) to a specified location.

Syntax: filepointer.seekg((no of bytes,reference point)

Note: For seekp and seekg three reference points are passed:

ios::beg - beginning of the file

ios::cur - current position in the file


ios::end - end of the file

Reading from and writing to a File

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();
}

Another Program for File Handling in C++


Example:

#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();
}

Another C++ Program to Print Hello GS to the Console


Example:

#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.

To understand its need, let's first look at the following program.

#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

Function Templates prevent us from defining separate functions performing the


same task for different data types. Let's look at the syntax of a function template
for the sum function in the above example.

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.

template <typename T> // declaring function template with template


parameter

This will tell the compiler that T is a type of template parameter.

#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.

template < class T > // declaring template parameter

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.

template // declaring template parameters

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.

The following example illustrates the same.

#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

Total marks of student2 : 103.9


Here, s1 and s2 are the two objects of class Student and marks1 and marks2 are
the marks of the students in first and second subject respectively.
Student s1 ( 45, 50 ); - This statement created an object s1 of class Student and
assigned 45 and 50 as marks1 and marks2 respectively. Since both are integer
values, therefore T is of type int. Also, the return value of the member function
totalMarks() is also of type int because the sum of two integers is an integer.
Student s2 ( 47.5, 56.4 ); - This created the second object s2 having the values of
both marks1 and marks2 float. Hence, T is a float in this case.

Das könnte Ihnen auch gefallen