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

Unit - V - OOPS

Uploaded by

Teena Kalbande
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)
8 views

Unit - V - OOPS

Uploaded by

Teena Kalbande
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/ 81

Unit - V

Streams and Files


Syllabus :
• Introduction to FILE. Reading and Writing to File objects.
Streams classes, Stream Errors, file pointers, error handling
in file I/O with member function, command line arguments,
Function templates, Class templates. Exception handling.
Streams
• In C++, streams represent a flow of data (characters) between a
program and an I/O device or file, facilitating input and output
operations. They are managed by classes like iostream for standard
input/output and fstream for file operations.
Data Flow:
• Streams are essentially sequences of bytes or characters that are
either flowing into a program (input) or out of a program (output).

I/O Devices:
• They enable programs to interact with various I/O devices, including
the keyboard, screen, files, and network sockets
Abstraction:
• Streams provide an abstract way to handle input and output, making
it easier to write portable code that can work with different I/O
devices.
• iostream:
• This library provides standard input/output streams, including:
• cin : Standard input stream (typically keyboard).
• cout: Standard output stream (typically screen).

• cerr: Standard error stream (typically screen).

• clog: Buffered error stream (typically screen).

• fstream:
• This library provides file input/output streams:
• ifstream: Input file stream (for reading from a file).
• ofstream : Output file stream (for writing to a file)
• #include <iostream> // For standard input/output streams
using namespace std;
int main() {
int age;

// Read input from the keyboard (standard input stream)


cout << "Enter your age: ";
cin >> age;

// Write output to the screen (standard output stream)


cout << "You are " << age << " years old." << endl;

return 0;
}
C++ Files and Streams
• In C++ programming we are using the iostream standard library, it
provides cin and cout methods for reading from input and writing to
output respectively.
• To read and write from a file we are using the standard C++ library
called fstream. Let us see the data types define in fstream library is:
fstream It is used to create files, write
information to files, and read
information from files.

ifstream It is used to read information from


files.

ofstream It is used to create files and write


information to the files.
C++ FileStream example: writing to a file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("testout.txt");
if (filestream.is_open())
{
filestream << "Welcome to GHRCE.\n";
filestream << "C++ Classes.\n";
filestream.close();
}
else cout <<"File opening is fail.";
return 0;
}
Output :

The content of a text file testout.txt is set with the data:


Welcome to GHRCE.
C++ Classes.
C++ FileStream example: reading from a file
#include <iostream>
#include <fstream>
using namespace std;
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;
}
Output:

Welcome to GHRCE.
C++ Classes.
C++ Read and Write Example
#include <fstream>
#include <iostream>
using namespace std;
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: Nakul Jain
Please Enter your age: 22
Reading from a text file: Nakul Jain 22
C++ getline()

• The cin is an object which is used to take input from the user but does
not allow to take the input in multiple lines. To accept the multiple
lines, we use the getline() function. It is a pre-defined function
defined in a <string.h> header file used to accept a line or a string
from the input stream until the delimiting character is encountered.
Syntax of getline() function:
• There are two ways of representing a function:
• The first way of declaring is to pass three parameters.
• istream& getline( istream& is, string& str, char delim );
• The above syntax contains three parameters, i.e., is, str, and delim.
• Where,
• is: It is an object of the istream class that defines from where to read the
input stream.
• str: It is a string object in which string is stored.
• delim: It is the delimiting character.
• Return value
• This function returns the input stream object, which is passed as a
parameter to the function.
• The second way of declaring is to pass two parameters.
• istream& getline( istream& is, string& str );
• The above syntax contains two parameters, i.e., is and str. This syntax
is almost similar to the above syntax; the only difference is that it
does not have any delimiting character.
• Where,
• is: It is an object of the istream class that defines from where to read
the input stream.
• str: It is a string object in which string is stored.
• Return value
• This function also returns the input stream, which is passed as a
parameter to the function.
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string name; // variable declaration
cout << "Enter your name :" << endl;
cin>>name;
cout<<"\nHello "<<name;
return 0;
}
Output:

Enter your name :


John Miller
Hello John
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string name; // variable declaration.
cout << "Enter your name :" << endl;
getline(cin,name); // implementing a getline() function
cout<<"\nHello "<<name;
return 0;
}
Output:

Enter your name :


John Miller
Hello John Miller
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string profile; // variable declaration
cout << "Enter your profile :" << endl;
getline(cin,profile,' ');
// implementing getline() function with a delimiting character.

cout<<"\nProfile is :"<<profile;
}
Output :-

Enter your profile :


Software Developer
Profile is: Software
Getline Character Array
• We can also define the getline() function for character array, but its
syntax is different from the previous one.
• Syntax
• istream& getline(char* , int size);
• In the above syntax, there are two parameters; one is char*, and the
other is size.
• Where,
• char*: It is a character pointer that points to the array.
• Size: It acts as a delimiter that defines the size of the array means
input cannot cross this size.
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
char fruits[50]; // array declaration
cout<< "Enter your favorite fruit: ";
cin.getline(fruits, 50); // implementing getline() function
cout << "\nYour favorite fruit is :"<<fruits << endl;
return 0;
}
Output :-

Enter your favorite fruit: Watermelon


Your favorite fruit is: Watermelon
C++ Stream Classes Structure
• In C++ there are number of stream classes for defining various
streams related with files and for doing input-output operations. All
these classes are defined in the file iostream.h.
• ios class is topmost class in the stream classes hierarchy. It is the base
class for istream, ostream, and streambuf class.

• istream and ostream serves the base classes for iostream class. The
class istream is used for input and ostream for the output.

• Class ios is indirectly inherited to iostream class


using istream and ostream. To avoid the duplicity of data and
member functions of ios class, it is declared as virtual base class when
inheriting in istream and ostream as
class istream: virtual public
ios
{
};
class ostream: virtual public
ios
{
};
• The ios class: The ios class is responsible for providing all input and
output facilities to all other stream classes.

• The istream class: This class is responsible for handling input stream.
It provides number of function for handling chars, strings and objects
such as get, getline, read, ignore, putback etc..
#include <iostream>
using namespace std;

int main()
{
char x;

// used to scan a single char


cin.get(x);

cout << x;
}
#include <iostream>
using namespace std;

int main()
{
char x;

// used to scan a single char


cin.get(x);

// used to put a single char onto the screen.


cout.put(x);
}
#include <iostream>
using namespace std;

int main()
{

// this function display


// ncount character from array
cout.write(“GHRCE STUDENTS", 5);
}
OUTPUT
GHRCE
#include <iostream>
using namespace std;
class demo {
public:
int dx, dy; // operator overloading using friend function
friend void operator>>(demo& d, istream& mycin)
{ // cin assigned to another object mycin
mycin >> d.dx >> d.dy;
} };
int main()
{
demo d;
cout << "Enter two numbers dx and dy\n";
// calls operator >> function and
// pass d and cin as reference
d >> cin; // can also be written as operator >> (d, cin) ;
cout << "dx = " << d.dx << "\tdy = " << d.dy;
}
Input:

4 5
Output:

Enter two numbers dx and dy 4 5


dx = 4 dy = 5
#include <iostream>
using namespace std;
class demo {
public:
int dx, dy;
demo()
{ dx = 4, dy = 5; } // operator overloading using friend function
friend void operator<<(demo& d, ostream& mycout)
{ // cout assigned to another object mycout
mycout << "Value of dx and dy are \n";
mycout << d.dx << " " << d.dy; } };
int main()
{ demo d; // default constructor is called
// calls operator << function and
// pass d and cout as reference
d << cout; // can also be written as operator << (d, cout) ;
}
Output:

Value of dx and dy are 4 5


Stream Error in C++
• In C++, cerr is the standard error stream used to output the errors. It
is an instance of the ostream class and is un-buffered, so it is used
when we need to display the error message immediately and does
not store the error message to display later. The ‘c’ in cerr refers to
“character” and ‘err’ means “error”, Hence cerr means “character
error”
#include <iostream>
using namespace std;

int main() {

// Printing error
cerr << "Welcome to GHRCE! :: cerr\n";

// Printing using cout


cout << "Welcome to GHRCE! :: cout";
return 0;
}
Error
Welcome to GHRCE! :: cerr
Welcome to GHRCE! :: cout
Syntax of cerr

cerr is defined inside the <iostream> header file and is similar to


the standard output stream.
cerr << “Error message”;
• Unbuffered Output: cerr outputs data immediately, which means it
does not store the data in a buffer. This makes it ideal for error
messages, as they need to be displayed right away.
• Separation of Error Messages: By using cerr, error messages can be
distinguished from regular program output, which typically uses cout.
This separation helps in logging and debugging.
#include <iostream>
using namespace std;

int main() {
int n1, n2;

cout << "Enter two numbers: ";


cin >> n1 >> n2;

// Displaying error using cerr


if (n2 == 0) {
cerr << "Error: Division by zero!" << endl;
return 1;
}

cout << "Result: " << n1 / n2 << endl;


return 0;
}
Output
Enter two numbers: 10 0
Error: Division by zero!
#include <bits/stdc++.h>
using namespace std;

int main() {

// Creating ostream to a log file


ofstream errorLog("error_log.txt");

// Redirect cerr to the file


cerr.rdbuf(errorLog.rdbuf());
cerr << "This is an error message written to a file." << endl;

errorLog.close();
return 0;
}
In the file error_log.txt:
This is an error message written to a file.
Exception handling in c++
• 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.

• 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++
• 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.
• Asynchronous: Exceptions that are beyond the program’s control,
such as disc failure, keyboard interrupts, etc.
• 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.
try {
// Code that might throw an exception
throw SomeExceptionType("Error message");
}
catch( ExceptionName e1 ) {
// catch block catches the exception that is thrown
from try block
}
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.
Why do we need Exception Handling in C++?
• Separation of Error Handling Code from Normal Code: There are always if-
else conditions to handle errors in traditional error handling codes. These
conditions and the code to handle errors get mixed up with the normal
flow. This makes the code less readable and maintainable. With try/catch
blocks, the code for error handling becomes separate from the normal
flow.

• Functions/Methods can handle only the exceptions they choose: A


function can throw many exceptions, but may choose to handle some of
them. The other exceptions, which are thrown but not caught, can be
handled by the caller. If the caller chooses not to catch them, then the
exceptions are handled by the caller of the caller.
In C++, a function can specify the exceptions that it throws using the throw
keyword. The caller of this function must handle the exception in some way
(either by specifying it again or catching it).

• Grouping of Error Types: In C++, both basic types and objects can be
thrown as exceptions. We can create a hierarchy of exception objects,
group exceptions in namespaces or classes, and categorize them according
to their types.
• C++ program to demonstate the use of try,catch and throw in
exception handling.
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{ // try block
try { int numerator = 10;
int denominator = 0;
int res; // check if denominator is 0 then throw
runtime
// error.
if (denominator == 0) {
throw runtime_error(
"Division by zero not allowed!"); }
// calculate result if no exception occurs
res = numerator / denominator;
//[printing result after division
cout << "Result after division: " << res << endl;
}
// catch block to catch the thrown exception
catch (const exception& e) {
// print the exception
cout << "Exception " << e.what() << endl;
}

return 0;
}
Output
Exception Division by zero not allowed!
// C++ program to demonstate the use of try,catch and throw in exception handling.
#include <iostream>
using namespace std;
int main() {
int x = -1; // Some code
cout << "Before try \n"; // try block
try {
cout << "Inside try \n";
if (x < 0) { // throwing an exception
throw x;
cout << "After throw (Never executed) \n"; } } // catch block
catch (int x) {
cout << "Exception Caught \n"; }
cout << "After catch (Will be executed) \n";
return 0; }
Output :

Before try
Inside try
Exception Caught
After catch (Will be
executed)
CASE - 1
• There is a special catch block called the ‘catch-all’ block, written as
catch(…), that can be used to catch all types of exceptions.
// C++ program to demonstate the use of catch all in exception handling.
#include <iostream>
using namespace std;
int main()
{ // try block
try { // throw
throw 10;
} // catch block
catch (char* excp) {
cout << "Caught " << excp;
}
// catch all
catch (...) {
cout << "Default Exception\n"; }
return 0; }
Output
Default Exception
CASE - 2
• Implicit type conversion doesn’t happen for primitive types.
//// C++ program to demonstate property 2: Implicit type
/// conversion doesn't happen for primitive types. // in exception handling.
#include <iostream>
using namespace std;
int main()
{
try { throw 'a';
}
catch (int x) {
cout << "Caught " << x;
}
catch (...) {
cout << "Default Exception\n"; }
return 0; }
Output

Default Exception
CASE - 3
• If an exception is thrown and not caught anywhere, the program
terminates abnormally.
• // C++ program to demonstate property 3: If an exception is
• // thrown and not caught anywhere, the program terminates
• // abnormally in exception handling.

#include <iostream>
using namespace std;

int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught ";
}
return 0;
}
Output

terminate called after throwing an


instance of 'char'
CASE - 4
• Unlike Java, in C++, all exceptions are unchecked, i.e., the compiler
doesn’t check whether an exception is caught or not (See this for
details). So, it is not necessary to specify all uncaught exceptions in a
function declaration. However,exception-handling it’s a
recommended practice to do so.
// C++ program to demonstate property 4 in exception handling.
#include <iostream>
using namespace std;
void fun(int* ptr, int x) {
if (ptr == NULL)
throw ptr;
if (x == 0)
throw x; /* Some functionality */
}
int main()
{ try {
fun(NULL, 0); }
catch (...) {
cout << "Caught exception from fun()";
}
return 0; }
Output
Caught exception from fun()
// C++ program to demonstate property 4 in better way
#include <iostream>
using namespace std;
void fun(int* ptr, int x) throw(
int*, int) // Dynamic Exception specification
{ if (ptr == NULL)
throw ptr;
if (x == 0)
throw x; /* Some functionality */
}
int main()
{ try {
fun(NULL, 0);
}
catch (...) {
cout << "Caught exception from fun()";
}
return 0; }
Output
Caught exception from fun()
CASE - 5
• In C++, try/catch blocks can be nested. Also, an exception can be re-
thrown using “throw; “.
• // C++ program to demonstrate try/catch blocks can be nested in C++
#include <iostream>
using namespace std;
int main()
{ // nesting of
try/catch
try {
try { throw 20; }
catch (int n) {
cout << "Handle Partially ";
throw; // Re-throwing an
exception
} }
catch (int n) {
cout << "Handle remaining ";
}
return 0; }
Output
Handle Partially Handle remaining
CASE - 6
• When an exception is thrown, all objects created inside the
enclosing try block are destroyed before the control is transferred to
the catch block.
// C++ program to demonstrate
#include <iostream>
using namespace std; //
Define a class named Test
class Test {
public: // Constructor of
Test
Test() { cout << "Constructor of Test " << endl; } // Destructor of Test
~Test() { cout << "Destructor of Test " << endl; }
};
int main()
{ try { // Create an object of class Test
Test t1; // Throw an integer exception with value 10
throw 10;
}
catch (int i) { // Catch and handle the integer exception
cout << "Caught " << i << endl;
} }
Output
Constructor of Test
Destructor of Test
Caught 10
Limitations of Exception Handling in C++
• Exceptions may break the structure or flow of the code as multiple
invisible exit points are created in the code which makes the code
hard to read and debug.
• If exception handling is not done properly can lead to resource leaks
as well.
• It’s hard to learn how to write Exception code that is safe.
• There is no C++ standard on how to use exception handling, hence
many variations in exception-handling practices exist.

You might also like