0% found this document useful (0 votes)
3 views

Unit V

Uploaded by

manishhadiabad70
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit V

Uploaded by

manishhadiabad70
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

File Handling in C++

Files store data permanently in a storage device. With file handling, the output from a
program can be stored in a file. Various operations can be performed on the data while in the
file.

A stream is an abstraction of a device where input/output operations are performed. You can
represent a stream as either a destination or a source of characters of indefinite length. This
will be determined by their usage. C++ provides you with a library that comes with methods
for file handling.

The fstream Library


The fstream library provides C++ programmers with three classes for working with files.
These classes include:

 ofstream– This class represents an output stream. It’s used for creating files and
writing information to files.
 ifstream– This class represents an input stream. It’s used for reading information from
data files.
 fstream– This class generally represents a file stream. It comes with ofstream/ifstream
capabilities. This means it’s capable of creating files, writing to files, reading from
data files.

To use the above classes of the fstream library, you must include it in your program as a
header file. You must also include the iostream header file.

How to Open Files


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::trunc If a file exists, the file elements should be truncated prior to its opening.

It is possible to use two modes at the same time. You combine them using the | (OR)
operator.

#include <iostream.h>
#include <fstream.h>
int main()
{
fstream my_file;
my_file.open("my_file", ios::out);
if (!my_file)
{
cout << "File not created!";
}
else
{
cout << "File created successfully!";
my_file.close();
}
return 0;
}

How to Close Files


Once a C++ program terminates, it automatically

 flushes the streams


 releases the allocated memory
 closes opened files.

The fstream, ofstream, and ifstream objects have the close() function for closing files. The
function takes this syntax:

void close();

How to Write to Files


You can write to file right from your C++ program. You use stream insertion operator (<<)
for this. The text to be written to the file should be enclosed within double-quotes.

#include <iostream.h>
#include <fstream.h>
int main()
{
fstream my_file;
my_file.open("my_file.txt", ios::out);
if (!my_file)
{
cout << "File not created!";
}
else
{
cout << "File created successfully!";
my_file << "Hello";
my_file.close();
}
return 0;
}

How to Read from Files


You can read information from files into your C++ program. This is possible using stream
extraction operator (>>). You use the operator in the same way you use it to read user input
from the keyboard. However, instead of using the cin object, you use the ifstream/fstream
object.

#include <iostream.h>
#include <fstream.h>
int main()
{
fstream my_file;
my_file.open("my_file.txt", ios::in);
if (!my_file)
{
cout << "No such file";
}
else {
char ch;

while (1)
{
my_file >> ch;
if (my_file.eof())

break;
cout << ch;
}

}
my_file.close();
return 0;
}
Exception Handling
In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters
during its execution. The process of handling these exceptions is called exception handling.
Using the exception handling mechanism, the control from one part of the program where
the exception occurred can be transferred to another part of the code.

So basically using exception handling in C++, we can handle the exceptions so that our
program keeps running.

What is a C++ Exception?


An exception is an unexpected problem that arises during the execution of a program our
program terminates suddenly with some errors/issues. Exception occurs during the running
of the program (runtime).

Types of C++ Exception

There are two types of exceptions in C++

1. Synchronous: Exceptions that happen when something goes wrong because of a


mistake in the input data or when the program is not equipped to handle the current
type of data it’s working with, such as dividing a number by zero.

2. Asynchronous: Exceptions that are beyond the program’s control, such as disc failure,
keyboard interrupts, etc.

Key Concepts of Exception Handling

C++ try and catch

C++ provides an inbuilt feature for Exception Handling. It can be done using the following
specialized keywords: try, catch, and throw with each having a different purpose.

Syntax

try {

// Code that might cause an exception

// If an error occurs, throw an exception

}
catch (exception_type e) {

// Code to handle the exception

1. try in C++

The try keyword represents a block of code that may throw an exception placed inside the try
block. It’s followed by one or more catch blocks. If an exception occurs, try block throws
that exception.

2. catch in C++

The catch statement represents a block of code that is executed when a particular exception
is thrown from the try block. The code to handle the exception is written inside the catch
block.

3. throw in C++

An exception in C++ can be thrown using the throw keyword. When a program encounters a
throw statement, then it immediately terminates the current function and starts finding a
matching catch block to handle the thrown exception.

Example:

#include <iostream>
using namespace std;

int main() {

double numerator, denominator, divide;

cout << "Enter numerator: ";


cin >> numerator;

cout << "Enter denominator: ";


cin >> denominator;

try {

// throw an exception if denominator is 0


if (denominator == 0)
throw 0;

// not executed if denominator is 0


divide = numerator / denominator;
cout << numerator << " / " << denominator << " = " << divide << endl;
}

catch (int num_exception) {


cout << "Error: Cannot divide by " << num_exception << endl;
}

return 0;
}

Understand the need for this concept in real-life situations

Suppose there is a form that is to be filled by the user, and the form there is a field called
age. This field should contain integers value only, but what if the user enters a character
value in it? In that case, the user will get an error. He gets this error because the programmer
has done exception handling in the code while making that form. This is where exception
handling is used.

So we have to consider all scenarios because users can also enter any invalid value. Our
program should be able to respond to that type of invalid value scenarios.

You might also like