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

Unit 5 Module 2 Data Hierarchy in Object

Uploaded by

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

Unit 5 Module 2 Data Hierarchy in Object

Uploaded by

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

Data hierarchy in object-oriented programming (OOP) -

Data hierarchy in object-oriented programming (OOP) is a way to model real-world


objects in code by breaking down their relationships. It's a basic concept in data and
database theory that helps to understand how data components are related.

 Hierarchical data structure: A way to organize data in a tree-like structure, where each
element has one parent node and zero or more child nodes. The top-level element is the root
node.
.
C++ Stream Classes Structure
L



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. Figure given below shows the hierarchy of these classes.
1. ios class is topmost class in the stream classes hierarchy. It is the base class
for istream, ostream, and streambuf class.

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

3. 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 _withassign classes are provided with extra functionality for the assignment
operations that’s why _withassign classes.

Facilities provided by these stream classes.

1. The ios class: The ios class is responsible for providing all input and output
facilities to all other stream classes.

2. 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..
Example:

 CPP14

#include <iostream>

using namespace std;

int main()

char x;

// used to scan a single char

cin.get(x);
cout << x;

Input:

g
Output:

g
The ostream class: This class is responsible for handling output stream. It provides
number of function for handling chars, strings and objects such as write, put etc..
Example:

 CPP14

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

1. Input:

g
Output:

The iostream: This class is responsible for handling both input and output stream as
both istream class and ostream class is inherited into it. It provides function of
both istream class and ostream class for handling chars, strings and objects such
as get, getline, read, ignore, putback, put, write etc..
Example:

 CPP14

#include <iostream>

using namespace std;

int main()

{
// this function display

// ncount character from array

cout.write("geeksforgeeks", 5);

Output:

geeks

istream_withassign class: This class is variant of istream that allows object


assignment. The predefined object cin is an object of this class and thus may be
reassigned at run time to a different istream object.
Example:To show that cin is object of istream class.

 CPP

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

45
Output:

Enter two numbers dx and dy


45
dx = 4 dy = 5

ostream_withassign class: This class is variant of ostream that allows object


assignment. The predefined objects cout, cerr, clog are objects of this class and thus
may be reassigned at run time to a different ostream object.
Example:To show that cout is object of ostream class.

 CPP14

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


}

Basics of File I/O and Stream Objects:-


Input/Ouput to and from files

 File input and file output is an essential in programming.


o Most software involves more than keyboard input and screen user
interfaces.
o Data needs to be stored somewhere when a program is not running, and
that means writing data to disk.
o For this, we need file input and file output techniques.
 Fortunately, this is EASY in C++!
o If you know how to do screen output with cout, and keyboard input
with cin, then you already know most of it!
o File I/O with streams works the same way. The primary difference is that
objects other than cout and cin will be used

Kinds of Files

 Formatted Text vs. Binary files


o A text file is simply made of readable text characters. It looks like the
output that is typically printed to the screen through the cout object
o A binary file contains unformatted data, saved in its raw memory format.
(For example, the integer 123456789 is saved as a 4-byte chunk of data,
the same as it's stored in memory - NOT as the 9 digits in this sentence).
 Sequential vs. Random Access files
o A sequential file is one that is typically written or read from start to
finish
o A random access file is one that stores records, all of the same size, and
can read or write single records in place, without affecting the rest of the
file
 (For now, we'll deal with sequential text files)
Creating file stream objects, and attaching to files

 cout and cin are objects


o cout is the standard output stream, usually representing the monitor. It is
of type ostream
o cin is the standard input stream, usually representing the keyboard. It is of
type istream
o ostream and istream are classes
o If you were to have declared them, you might have written:
o ostream cout;
o istream cin;

 To create file stream objects, we need to include the <fstream> library:


 #include <fstream>
 using namespace std;
 This library has classes ofstream ("output file stream") and ifstream ("input file
stream"). Use these to declare file stream objects:
 ofstream out1, bob; // create file output streams, called out1 and bob
 ifstream in1, joe; // create file input streams, called in1 and joe
 File stream objects need to be attached to files before they can be used. Do this
with a member function called open, which takes in the filename as an argument:
 out1.open("outfile1.txt"); // for ofstreams, these calls create
 bob.open("clients.dat"); // brand new files for output

 in1.open("infile1.txt"); // for ifstreams, these calls try to open
 joe.open("clients.dat"); // existings files for input
 Will open() always work?
o For an input file, what if the file doesn't exist? doesn't have read
permission?
o For an output file, what if the directory is not writable? What if it's an
illegal file name?

 Since it's possible for open() to fail, one should always check to make sure there's
a valid file attached
o One easy way is to test the true/false value of the stream object itself. A
stream that is not attached to a valid file will evaluate to "false"
o if (!in1) // if in1 not attached to a valid input source, abort
o {
o cout << "Sorry, bad file.";
o exit(0); // special system call to abort program
o // may require <cstdlib> to be included
o }

 When finished with a file, it can be detached from the stream object with the
member function close():
 in1.close();
 out1.close();
 bob.close();

Note that the close function simply closes the file. It does not get rid of the
stream object. The stream object can now be used to attach to another file, if
desired:

in1.open("infile2.txt");

==========================
File Handling through C++ Classes

Last Updated : 11 Oct, 2024

File handling is used to store data permanently in a computer. Using file


handling we can store our data in secondary memory (Hard disk).

How to achieve the File Handling

For achieving file handling we need to follow the following steps:-

STEP 1-Naming a file

STEP 2-Opening a file

STEP 3-Writing data into the file

STEP 4-Reading data from the file

STEP 5-Closing a file.

Streams in C++ :-

We give input to the executing program and the execution program gives back
the output. The sequence of bytes given as input to the executing program and
the sequence of bytes that comes as output from the executing program are
called stream. In other words, streams are nothing but the flow of data in a
sequence.

The input and output operation between the executing program and the devices
like keyboard and monitor are known as “console I/O operation”. The input
and output operation between the executing program and files are known as
“disk I/O operation”.

Classes for File stream operations :-

The I/O system of C++ contains a set of classes which define the file handling
methods. These include ifstream, ofstream and fstream classes. These classes
are derived from fstream and from the corresponding iostream class. These
classes, designed to manage the disk files, are declared in fstream and therefore
we must include this file in any program that uses files. File handling is
essential for data storage and retrieval in applications. The C++ Course
provides practical tutorials on how to manage file operations using C++ classes,
enhancing your file management skills.

1. ios:-

ios stands for input output stream.

This class is the base class for other classes in this class hierarchy.

This class contains the necessary facilities that are used by all the other derived
classes for input and output operations.

2. istream:-

istream stands for input stream.

This class is derived from the class ‘ios’.


This class handle input stream.

The extraction operator(>>) is overloaded in this class to handle input streams


from files to the program execution.

This class declares input functions such as get(), getline() and read().

3. ostream:-

ostream stands for output stream.

This class is derived from the class ‘ios’.

This class handle output stream.

The insertion operator(<<) is overloaded in this class to handle output streams


to files from the program execution.

This class declares output functions such as put() and write().

4. streambuf:-

This class contains a pointer which points to the buffer which is used to manage
the input and output streams.

5. fstreambase:-

This class provides operations common to the file streams. Serves as a base for
fstream, ifstream and ofstream class.

This class contains open() and close() function.

6. ifstream:-
This class provides input operations.

It contains open() function with default input mode.

Inherits the functions get(), getline(), read(), seekg() and tellg() functions from
the istream.

7. ofstream:-

This class provides output operations.

It contains open() function with default output mode.

Inherits the functions put(), write(), seekp() and tellp() functions from the
ostream.

8. fstream:-

This class provides support for simultaneous input and output operations.

Inherits all the functions from istream and ostream classes through iostream.

9. filebuf:-

Its purpose is to set the file buffers to read and write.

We can also use file buffer member function to determine the length of the file.

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream
available in fstream headerfile.

ofstream: Stream class to write on files

ifstream: Stream class to read from files


fstream: Stream class to both read and write from/to files.

Now the first step to open the particular file for read or write operation. We can
open file by

1. passing file name in constructor at the time of object creation

2. using the open method

For e.g.

Open File by using constructor

ifstream (const char* filename, ios_base::openmode mode = ios_base::in);

ifstream fin(filename, openmode) by default openmode = ios::in

ifstream fin(“filename”);

Open File by using open method

Calling of default constructor

ifstream fin;

fin.open(filename, openmode)

fin.open(“filename”);
Modes :

Member Constant Stands For Access

ios::in input File open for reading: the internal stream buffer supports
input operations.

ios::out output File open for writing: the internal stream buffer
supports output operations.

ios::binary binary Operations are performed in binary mode rather than


text.

ios::ate at end The output position starts at the end of the file.

ios::app append All output operations happen at the end of the file,
appending to its existing contents.

ios::trunc truncate Any contents that existed in the file before it is open
are discarded.

ios::nocreate

Do not create

Does not allow to create new file if it does not exist.

ios::noreplace
Do not replace

Does not replace old file with new file.

Both ios::app and ios::ate take us to the end of the file when it is opened. The
difference between the two modes is that ios :: app allow us to add data to the
end of the file only, while ios :: ate mode permits us add data or to modify the
existing data anywhere in the file.

Default Open Modes :

ifstream ios::in

ofstream ios::out

fstream ios::in | ios::out

Problem Statement : To read and write a File in C++.

Examples:

Input :

Welcome in GeeksforGeeks. Best way to learn things.

-1

Output :
Welcome in GeeksforGeeks. Best way to learn things.

Below is the implementation by using ifstream & ofstream classes.

/* File Handling with C++ using ifstream & ofstream class object*/

/* To write the Content in File*/

/* Then to read the content of file*/

#include <iostream>

/* fstream header file for ifstream, ofstream,

fstream classes */

#include <fstream>

using namespace std;

// Driver Code

int main()

// Creation of ofstream class object

ofstream fout;

string line;
// by default ios::out mode, automatically deletes

// the content of file. To append the content, open in ios:app

// fout.open("sample.txt", ios::app)

fout.open("sample.txt");

// Execute a loop If file successfully opened

while (fout) {

// Read a Line from standard input

getline(cin, line);

// Press -1 to exit

if (line == "-1")

break;

// Write line in file

fout << line << endl;

// Close the File

fout.close();
// Creation of ifstream class object to read the file

ifstream fin;

// by default open mode = ios::in mode

fin.open("sample.txt");

// Execute a loop until EOF (End of File)

while (getline(fin, line)) {

// Print line (read from file) in Console

cout << line << endl;

// Close the file

fin.close();

return 0;
}

======================



File handling is used to store data permanently in a computer. Using file handling
we can store our data in secondary memory (Hard disk).
How to achieve the File Handling
For achieving file handling we need to follow the following steps:-
STEP 1-Naming a file
STEP 2-Opening a file
STEP 3-Writing data into the file
STEP 4-Reading data from the file
STEP 5-Closing a file.
Streams in C++ :-
We give input to the executing program and the execution program gives back the
output. The sequence of bytes given as input to the executing program and the
sequence of bytes that comes as output from the executing program are called
stream. In other words, streams are nothing but the flow of data in a sequence.
The input and output operation between the executing program and the devices like
keyboard and monitor are known as “console I/O operation”. The input and output
operation between the executing program and files are known as “disk I/O
operation”.
Classes for File stream operations :-
The I/O system of C++ contains a set of classes which define the file handling
methods. These include ifstream, ofstream and fstream classes. These classes are
derived from fstream and from the corresponding iostream class. These classes,
designed to manage the disk files, are declared in fstream and therefore we must
include this file in any program that uses files. File handling is essential for data
storage and retrieval in applications.
1. ios:-
 ios stands for input output stream.
 This class is the base class for other classes in this class hierarchy.
 This class contains the necessary facilities that are used by all the other derived
classes for input and output operations.

2. istream:-
 istream stands for input stream.
 This class is derived from the class ‘ios’.
 This class handle input stream.
 The extraction operator(>>) is overloaded in this class to handle input streams
from files to the program execution.
 This class declares input functions such as get(), getline() and read().

3. ostream:-
 ostream stands for output stream.
 This class is derived from the class ‘ios’.
 This class handle output stream.
 The insertion operator(<<) is overloaded in this class to handle output streams to
files from the program execution.
 This class declares output functions such as put() and write().
4. streambuf:-
 This class contains a pointer which points to the buffer which is used to manage
the input and output streams.
5. fstreambase:-
 This class provides operations common to the file streams. Serves as a base for
fstream, ifstream and ofstream class.
 This class contains open() and close() function.
6. ifstream:-
 This class provides input operations.
 It contains open() function with default input mode.
 Inherits the functions get(), getline(), read(), seekg() and tellg() functions from
the istream.
7. ofstream:-
 This class provides output operations.
 It contains open() function with default output mode.
 Inherits the functions put(), write(), seekp() and tellp() functions from the
ostream.
8. fstream:-
 This class provides support for simultaneous input and output operations.
 Inherits all the functions from istream and ostream classes through iostream.
9. filebuf:-
 Its purpose is to set the file buffers to read and write.
 We can also use file buffer member function to determine the length of the file.

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream
available in fstream headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Now the first step to open the particular file for read or write operation. We can open
file by
1. passing file name in constructor at the time of object creation
2. using the open method
For e.g.
Open File by using constructor
ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
ifstream fin(“filename”);
Open File by using open method
Calling of default constructor
ifstream fin;
fin.open(filename, openmode)
fin.open(“filename”);

Modes :
Member Stands
Constant For Access

File open for reading: the internal stream buffer


ios::in input
supports input operations.

File open for writing: the internal stream buffer


ios::out output
supports output operations.

Operations are performed in binary mode rather than


ios::binary binary
text.

ios::ate at end The output position starts at the end of the file.

All output operations happen at the end of the file,


ios::app append
appending to its existing contents.

Any contents that existed in the file before it is open


ios::trunc truncate
are discarded.

Do not
ios::nocreate Does not allow to create new file if it does not exist.
create

Do not
ios::noreplace Does not replace old file with new file.
replace

Both ios::app and ios::ate take us to the end of the file when it is opened. The
difference between the two modes is that ios :: app allow us to add data to the end of
the file only, while ios :: ate mode permits us add data or to modify the existing data
anywhere in the file.
Default Open Modes :
ifstream ios::in

ofstream ios::out

fstream ios::in | ios::out

Problem Statement : To read and write a File in C++.


Examples:
Input :
Welcome in GeeksforGeeks. Best way to learn things.
-1
Output :
Welcome in GeeksforGeeks. Best way to learn things.
Below is the implementation by using ifstream & ofstream classes.
C++
/* File Handling with C++ using ifstream & ofstream class object*/
/* To write the Content in File*/
/* Then to read the content of file*/
#include <iostream>

/* fstream header file for ifstream, ofstream,


fstream classes */
#include <fstream>

using namespace std;

// Driver Code
int main()
{
// Creation of ofstream class object
ofstream fout;

string line;

// by default ios::out mode, automatically deletes


// the content of file. To append the content, open in ios:app
// fout.open("sample.txt", ios::app)
fout.open("sample.txt");

// Execute a loop If file successfully opened


while (fout) {
// Read a Line from standard input
getline(cin, line);

// Press -1 to exit
if (line == "-1")
break;

// Write line in file


fout << line << endl;
}

// Close the File


fout.close();

// Creation of ifstream class object to read the file


ifstream fin;

// by default open mode = ios::in mode


fin.open("sample.txt");

// Execute a loop until EOF (End of File)


while (getline(fin, line)) {

// Print line (read from file) in Console


cout << line << endl;
}

// Close the file


fin.close();

return 0;
}

You might also like