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

Module 4 C++ Notes

Uploaded by

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

Module 4 C++ Notes

Uploaded by

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

MODULE-4

C++ STREAM CLASSES HIERARCHY

The I/O hierarchy shown below is usually mentioned without the prefix basic_, that is, basic_ ios
is usually referred to as ios. The ios_base class contains the details not needed for templatization.
basic_ios and its descendants are all templatized. basic_streambuf provides the mechanism to
access the stream using lower-level functions. It also provides services to other classes. There are
a few more items in the hierarchy that are not mentioned here.

ios class − This class is the base class for all stream classes. The streams can be input or output
streams. This class defines members that are independent of how the templates of the class are
defined.

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

istream Class − The istream class handles the input stream in c++ programming language.
These input stream objects are used to read and interpret the input as a sequence of characters.
The cin handles the input.
• 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().

ostream class − The ostream class handles the output stream in c++ programming language.
These output stream objects are used to write data as a sequence of characters on the screen. cout
and puts handle the out streams in c++ programming language.

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

streambuf class- It is used to get current character and returns the character at the current
position of the controlled input sequence, without modifying the current position.

ofstream class-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.
iostream class- iostream stands for standard input-output stream. This header file contains
definitions of objects like cin, cout, cerr, etc.

ifstream class- 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.
fstream class- This data type represents the file stream generally, and has the capabilities of
both ofstream and ifstream which means it can create files, write information to files, and read
information from files.

• This class provides support for simultaneous input and output operations.
• Inherits all the functions from istream and ostream classes through iostream.

TEXT FILES

Text files are easier to deal with. A program where a fi le accepts a few lines as input and then
displays those lines one by one. The simplest of functions to be used for this operation.

1. Defining Files
Files can be defined in three possible types.
1. ifstream <filename> (input file stream)
2. ofstream <filename> (output file stream)
3. fstream <filename> (I/O file stream)

The ifstream fi le is a read-only fi le, and one can only read from the fi le defined as ifstream.
The ofstream fi le is an output-only fi le, and one can only write to the fi le defined as ofstream.
The fstream fi le is used for both input and output.

2. Opening Files
Files can be opened using constructors and open functions. Using constructors, one can open a file
with a statement such as
ofstream EntryFile("FewLines.dat")

After defining FewLines.dat to be a physical name for EntryFile logical name, the data written to
the EntryFile will be written to FewLines.dat. The logical name (EntryFile) will vanish when the
program is over, but the physical file name will be there until somebody renames or deletes the
file.
The fi le modes have not been specified. It is assumed to be ios::out (output mode) when the object
of ofstream class (the EntryFile) is defined. Now, take a look at the following statement:
ifstream DisplayFile("FewLines.dat");

3. Reading from and Writing to Files


It is very simple to read from and write to a fi le. Overloaded << and >> operators need to be
used as they were used with cout and cin.

4. Closing Files
The function close() is used without any arguments to close a fi le. The allocated fi le handle is
deallocated and the buffers are flushed when a fi le is closed.

5. Using Text Files


A simple program to read a few lines and then display each word in a different line.

PROGRAM : Working on a text file


#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string InputLine, OutputLine;
ofstream EntryFile("FewLines.dat")
cout << "Input :" << endl;
while(true)
{
cin >> InputLine;
if(InputLine == "End") break;
EntryFile << InputLine << endl;
}
EntryFile.close();
cout << "Output: " << endl;
ifstream DisplayFile("FewLines.dat");
while(IDisplayFile.eof())
{
DisplayFile >> OutputLine;
cout << OutputLine << "\n";
}
DisplayFile.close();
return 0;
}
Input
It was a fi ght
for pride and ego
for one
It was a fi ght for
duty and self-respect
for another
who won it at the End
Output
It
was
afi
ght
...
who
won
it
at
the
Program: Using get() and put( )
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#include <iomanip>
int main()
{
char ch;
ofstream EntryFile("FewLines.dat");
while(true)
{
cin.get(ch);
if(ch == '$') break;
EntryFile << ch;
}
EntryFile.close();
ifstream DisplayFile("FewLines.dat");
while(!DisplayFile.eof())
{
// Do not skip white space
DisplayFile.unsetf(ios::skipws);
DisplayFile >> ch;
cout << ch;
}
DisplayFile.close();
return 0;
}
Input
The battle
between One and Another
is
between light and darkness
between truthfulness and falsehood
between duty and ego
$
Output
The battle
between One and Another
is
between light and darkness
between truthfulness and falsehood
between duty and ego
Program: Using getline( )
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
char InputLine[80], OutputLine[80];
ofstream EntryFile("FewLines.dat");
while(true)
{
cin.getline(InputLine, 80);
if(!strcmp(InputLine, "End")) break;
EntryFile << InputLine << endl;
}
EntryFile.close();
ifstream DisplayFile("FewLines.dat");
while(!DisplayFile.eof())
{
DisplayFile.getline(OutputLine, 80);
cout << OutputLine << endl;
}
DisplayFile.close();
return 0;
}
Input
Imagination is
more important
than knowledge
End
Output
Imagination is more important than knowledge

BINARY FILES
These fi les are more useful for storing structures of information.

1. Opening a Binary File


A binary file can be opened using a constructor. The constructors for ofstream and ifstream that
we have seen so far are acceptable for text fi les. For binary fi les, another constructor with two
arguments is needed. The first argument is the name of the fi le and the second one is the fi le
mode. Look at the following statements, which are examples for both the methods.

// Using open methods


ofstream MCA_StudFile_Out;
MCA_StudFile_Out.open("MCA.dat", ios::out | ios::binary | ios::trunc);
// Using constructor
ifstream MCA_StudFile_In("MCA.dat", ios::in | ios::binary);
The first example is using the open method and the second one is using a constructor.
The same effect can be achieved by writing either of the following:
ofstream MCA_StudFile_Out("MCA.dat", ios::out | ios::binary | ios::trunc);
ifstream MCA_StudFile_In;
MCA_StudFile_In.open("MCA.dat", ios::in | ios::binary);

Constructor calls and open functions produce similar effects. Only in the case when the fi le is
already open and there is a need to reopen the fi le with new modes, one may type close() and then
use .open method to open the same fi le in different modes. Note that pipes (|) are used in the
second argument to add multiple nodes.
2. Reading from and Writing to Binary Files
Two member functions for ifstream and ofstream objects are useful in reading and writing.
Both of them have similar syntax. They are:
OfstreamFileObject.write((char *) &<the object>, sizeof(<the same object>))
for writing in the file
IfStreamFileObject.read((char *) &<the object>, sizeof(<the same object>))
for reading from the file.
It is important to understand that the fi le read and write is performed objectwise and not
elementwise. One reads the complete object from the file or writes the complete object to the file
using a single read or write.
Here, both reading the object from the keyboard and writing it to the screen are done elementwise.
3. Closing Binary Files

Closing of binary fi les is similar to closing text fi les. A close() function is needed to close the
binary fi le.
Example for closing a file is
MCA_StudFile_Out.close();

The syntax for closing a fi le is


FileObject.close()
It also deallocates the fi le handle and fl ushes the allocated buffers as in the case of text files.

4. Using Binary Files


Program: Writing to a binary file
#include <iostream>
#include <fstream>
using namespace std;
struct student
{
int RollNo;
char Name[30];
char Address[40];
};
void ReadStudent(student & TempStud)
{
cout << "\n Enter roll no.: ";
cin >> TempStud.RollNo;
cout << "\n Enter name: ";
cin >> TempStud.Name;
cout << "\n Enter address: ";
cin >> TempStud.Address;
cout << "\n";
}
int main()
{
struct student MCA_Student_Out;
ofstream MCA_StudFile_Out;
MCA_StudFile_Out.open("MCA.dat", ios::out | ios::binary | ios::trunc);
if(!MCA_StudFile_Out.is_open())
cout << "File cannot be opened \n";
char Continue = 'y';
do
{
ReadStudent(MCA_Student_Out);
MCA_StudFile_Out.write((char*) &MCA_Student_Out, sizeof(struct student));
if(MCA_StudFile_Out.fail())
cout << "File write failed";
cout << "Do you want to continue? (y/n): ";
cin >> Continue;
} while(Continue != 'n');
MCA_StudFile_Out.close();
return 0;
}
Input
Enter roll no.: 1
Enter name: Lara
Enter address: West Indies
Do you want to continue? (y/n): y
Enter roll no.: 2
Enter name: Ranatunga
Enter address: Sri Lanka
Do you want to continue? (y/n): y
Enter roll no.: 3
Enter name: Steffi
Enter address: Germany
Do you want to continue? (y/n): n
Program: Reading from a binary file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct student
{
int RollNo;
char Name[30];
char Address[40];
};
void WriteStudent(student TempStud)
{
cout << "\n The roll no.: ";
cout << TempStud.RollNo;
cout << "\n The name: ";
cout << TempStud.Name;
cout << "\n The address: ";
cout << TempStud.Address;
cout << "\n";
}
int main()
{
struct student MCA Student In;
ifstream MCA_StudFile_In("MCA.dat", ios::in | ios::binary);
while(!MCA_StudFile_In.eof())
{
MCA_StudFile_In.read((char*) &MCA_Student_In, sizeof(struct student));
if(MCA_StudFile_In.fail())
break;
WriteStudent(MCA_Student_In);
}
MCA_StudFile_In.close();
return 0;
}
Output
The roll no.: 1
The name: Lara
The address: West Indies
The roll no.: 2
The name: Ranatunga
The address Sri Lanka
The roll no.: 3
The name: Steffi
The address Germany

You might also like