0% found this document useful (0 votes)
26 views19 pages

Unit 5

Uploaded by

sy9193355161
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)
26 views19 pages

Unit 5

Uploaded by

sy9193355161
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/ 19

UNIT-5

File Handling In C++


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

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
open() function
Syntax
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. The following modes are
used as per the requirements.

Modes Description
in: Opens the file to read(default for ifstream)
out: Opens the file to write(default for ofstream)
binary: Opens the file in binary mode
app: Opens the file and appends all the outputs at the end
ate: Opens the file and moves the control to the end of the file
trunk: Removes the data in the existing file
nocreate: Opens the file only if it already exists
noreplace: Opens the file only if it does not already exist

Example
fstream new_file;
new_file.open(“Sample.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;
new_file.open(“Sample.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.h>
#include <fstream.h>
int main()
{
fstream new_file;
new_file.open("Sample", ios::out);
if(!Sample)
{
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 ‘Sample’ 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”.

Writing to a File
Example:
#include <iostream.h>
#include <fstream.h>
int main()
{
fstream new_file;
new_file.open("Sample.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 “Sample” 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.

Reading from a File


Example

#include <iostream.h>
#include <fstream.h>
int main()
{
fstream new_file;
new_file.open("Sample.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. Sample.
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.

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

Syntax:
File_Pointer.close()

Example

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

The file gets closed.

C++ FileStream example: writing to a file

Let's see the simple example of writing to a text file testout.txt using C++ FileStream
programming.
#include <iostream.h>
#include <fstream.h>
int main ()
{
ofstream filestream("testout.txt");
if (filestream.is_open())
{
filestream << "Welcome to all in class.\n";
filestream << "C++ Tutorial.\n";
filestream.close();
}
else cout <<"File opening is fail.";
getch();
return 0;
}

Output
The content of a text file testout.txt is set with the data:
Welcome to all in class.
C++ Tutorial.
C++ FileStream example: reading from a file
Let's see the simple example of reading from a text file testout.txt using C++ FileStream
programming.
#include <iostream.h>
#include <fstream.h>
int main ()
{
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while ( getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else
{
cout << "File opening is fail."<<endl;
}
return 0;
}

Note: Before running the code a text file named as "testout.txt" is need to be created and the
content of a text file is given below:
Welcome to all students.
C++ Tutorial.
Output:
Welcome to all students.
C++ Tutorial.

C++ Read and Write Example

Let's see the simple example of writing the data to a text file testout.txt and then reading the data
from the file using C++ FileStream programming.
#include <fstream.h>
#include <iostream.h>
int main ()
{
char input[75];
ofstream os;
os.open("testout.txt");
cout <<"Writing to a text file:" << endl;
cout << "Please Enter your name: ";
cin.getline(input, 100);
os << input << endl;
cout << "Please Enter your age: ";
cin >> input;
cin.ignore();
os << input << endl;
os.close();
ifstream is;
string line;
is.open("testout.txt");
cout << "Reading from a text file:" << endl;
while (getline (is,line))
{
cout << line << endl;
}
is.close();
return 0;
}

Output:
Writing to a text file:
Please Enter your name: Rahul Kumar
Please Enter your age: 22
Reading from a text file: Rahul Kumar
22
Namespaces

Namespaces in C++ are used to organize too many classes so that it can be easy to handle the
application.
Namespace provide the space where we can define or declare identifier i.e. variable, method,
classes. It is the container for identifiers. It puts the names of its members in a distinct space so
that they don’t conflict with the names in other namespaces or global namespace.
Using namespace, we can define the space or context in which identifiers are defined i.e.
variable, method, classes. In essence, a namespace defines a scope.
For accessing the class of a namespace, we need to use namespacename::classname. We can
use using keyword so that we don't have to use complete name all the time.
In C++, global namespace is the root namespace. The global::std will always refer to the
namespace "std" of C++ Framework.

Defining a Namespace:
A namespace definition begins with the keyword namespace followed by the namespace name as
follows:
namespace namespace_name
{
// code declarations i.e. variable (int a;)
functions (void add();)
classes ( class student{};)
}
It is to be noted that, there is no semicolon (;) after the closing brace.
To call the namespace-enabled version of either function or variable, prepend the namespace
name as follows:
namespace_name: :code; // code could be variable , function or class.

The using directive:


You can also avoid prepending of namespaces with the using namespace directive. This directive
tells the compiler that the subsequent code is making use of names in the specified namespace.
The namespace is thus implied for the following code:
#include <iostream>
using namespace std;
// first name space
namespace first_space
{
void func()
{
cout << "Inside first_space" << endl;
}
}

// second name space


namespace second_space
{
void func()
{
cout << "Inside second_space" << endl;
}
}
using namespace first_space;
int main ()
{
// This calls function from first name space.
func();
return 0;
}

Output
Inside first_space
Nested Namespaces:
Namespaces can be nested where you can define one namespace inside another name space as
follows:
SYNTAX:
namespace namespace_name1
{
// code declarations
namespace namespace_name2
{
// code declarations
}
}

we can access members of nested namespace by using resolution operators as follows:


// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace_name1
using namespace namespace_name1;

In the above statements if you are using namespace_name1, then it will make elements of
namespace_name2 available in the scope as follows:
#include <iostream>
using namespace std;
// first name space
namespace first_space
{
void func()
{
cout << "Inside first_space" << endl;
}
// second name space
namespace second_space
{
void func()
{
cout << "Inside second_space" << endl;
}
}
}
using namespace first_space::second_space;
int main ()
{
// This calls function from second name space.
func();

return 0;
}

Output
Inside second_space

Let us see how namespace scope the entities including variable and functions:
#include <iostream>
using namespace std;
// first name space
namespace first_space
{
void func()
{
cout << "Inside first_space" << endl;
}
}
// second name space
namespace second_space
{
void func()
{
cout << "Inside second_space" << endl;
}
}

int main ()
{
// Calls function from first name space.
first_space :: func();
// Calls function from second name space.
second_space :: func();
return 0;
}

Output
Inside first_space
Inside second_space

Consider the following C++ program:

// A program to demonstrate need of namespace


int main()
{
int value;
value = 0;
double value; // Error here
value = 0.0;
}

Output :
Compiler Error:
'value' has a previous declaration as 'int value'

In each scope, a name can only represent one entity. So, there cannot be two variables with the
same name in the same scope. Using namespaces, we can create two variables or member
functions having the same name.

// Here we can see that more than one variables are being used without reporting any error.
// That is because they are declared in the different namespaces and scopes.
#include <iostream.h>
using namespace std;
// Variable created inside namespace
namespace first
{
int val = 500;
}
// Global variable
int val = 100;
int main()
{
// Local variable
int val = 200;
// These variables can be accessed from outside the namespace using the scope
// operator ::
cout << first::val << '\n';
return 0;
}

Output
500

Exception Handling

An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero. Exceptions provide a way to transfer control from one part of a
program to another. C++ exception handling is built upon three keywords: try, catch, and throw.
 throw: A program throws an exception when a problem shows up. This is done using a
throw keyword.
 catch: A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
 try: A try block identifies a block of code for which particular exceptions will be
activated. It is followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch is as follows:
try
{
// protected code
}
catch( ExceptionName e1 )
{
// catch block
}
catch( ExceptionName e2 )
{
// catch block
}
catch( ExceptionName eN )
{
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in case your try
block raises more than one exception in different situations.

Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement. The operand of
the throw statement determines a type for the exception and can be any expression and the type
of the result of the expression determines the type of exception thrown.
Following is an example of throwing an exception when dividing by zero condition occurs:
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions
The catch block following the try block catches any exception. You can specify what type of
exception you want to catch and this is determined by the exception declaration that appears in
parentheses following the keyword catch.
try
{
// protected code
}
catch( ExceptionName e )
{
// code to handle ExceptionName exception
}

Above code will catch an exception of ExceptionName type. If you want to specify that a catch
block should handle any type of exception that is thrown in a try block, you must put an ellipsis,
..., between the parentheses enclosing the exception declaration as follows:
try
{
// protected code
}
catch(...)
{
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we catch it in
catch block.

#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try
{
z = division(x, y);
cout << z << endl;
}
catch (const char* msg)
{
cerr << msg << endl;
}
return 0;
}
Because we are raising an exception of type const char*, so while catching this exception, we
have to use const char* in catch block. If we compile and run above code, this would produce the
following result:
Division by zero condition!

You might also like