bplck-205d-module-4
bplck-205d-module-4
MODULE-4
INPUT/OUTPUT STREAMS (C++ STREAMS)
C++ comes with libraries that provide us with many ways for performing input and output. In C++
input and output are performed in the form of a sequence of bytes or more commonly known
as streams.
Streams are defined in the streams library header file <iostream> and implemented in the iostream
library.
• Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to
the main memory then this process is called input.
• Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to
device( display screen ) then this process is called output
Input stream
Input device
Program
Output device
Output stream
Fig. Data streams
➢ Stream can be act as a source from which the input data can be obtained or as a destination to
which the output data can be sent.
➢ The source stream that provides data to the program is called the input stream.
➢ The destination stream that receives output from the program is called the output stream.
➢ A program extracts bytes from an input stream
➢ A program inserts bytes into an output stream.
➢ The data in the input stream can come from the keyboard or any other storage device.
➢ The data in the output stream can go to the screen or any other storage device.
➢ A stream acts as an interface between the program and the input/output device.
• Standard output stream (cout): Usually the standard output device is the display screen.
The C++ cout statement is the instance of the ostream class. It is used to produce output on
the standard output device which is usually the display screen. The data needed to be
displayed on the screen is inserted in the standard output stream (cout) using the insertion
operator(<<).
• Un-buffered standard error stream (cerr): The C++ cerr is the standard error stream that
is used to output the errors. This is also an instance of the iostream class. As cerr in C++ is
un-buffered so it is used when one needs to display the error message immediately. It does
not have any buffer to store the error message and display it later.
The main difference between cerr and cout comes when you would like to redirect output
using “cout” that gets redirected to file if you use “cerr” the error doesn’t get stored in
file.(This is what un-buffered means ..It cant store the message)
• (buffered standard error stream (clog): This is also an instance of ostream class and used
to display errors but unlike cerr the error is first inserted into a buffer and is stored in the
buffer until it is not fully filled. or the buffer is not explicitly flushed (using flush()). The
error message will be displayed on the screen too.
Example:
1.char data;
// get() return the character value and assign to data variable
data = cin.get();
2. char c;
// directly assign value to c
cin.get(c);
put():-
The put() function is a member of the ostream class, and used to output a line of text, character by
character. For example,
cout.put(‘x’);
in the above statement displays the character x and
cout.put(ch);
Here displays the value of variable ch.
The variable ch must contain a character value. We can also use a number as an argument to the
function put(). For example,
cout.put(68);
displays the character D. This statement will convert the int value 68 to a char value and display
the character whose ASCII value is 68. The following segment of a program reads a line of the text
from keyboard and also displays it on the screen.
char c;
cin.get(c); // in this statement read a character
while(c ! = ‘\n’)
{
cout.put(c); // displays the character on screen
cin.get(c);
}
#include <iostream>
using namespace std;
int main()
{
int count = 0;
char c;
cout << "INPUT TEXT\n";
cin.get(c);
while (c != '\n')
{
cout.put(c);
count++;
cin.get(c);
}
cout << "\nNumber of characters = " << count << "\n";
return 0;
}
PROGRAM OUTPUT
Input
Object Oriented Programming
output
Object Oriented Programming
Number of characters = 27
int main()
{
char line[100];
cin.getline(line, 10);
cout.write(line, 5);
cout << endl;
cout.write(line, 20);
cout << endl;
return 0;
}
The ios class contains several member functions that are used to perform formmate IO operations.
width(): The width method is used to set the required field width. The output will be displayed in the
given width. The default width of your output will be just enough space to print the number,
character, or string in the output buffer. You can change this by using width(). Because width() is a
member function, it must be invoked with a cout object. It only changes the width of the very next
output field and then immediately reverts to the default.
example:-
cout.width(5);
cout<<”123”;
output:-
1 2 3
precision(): The precision method is used to set the number of the decimal point to a float value
By default, the floating numbers are printed with six digits after the decimal point.
To specify the number of digits after the decimal point using the precision()
cout.precision();
Where d is the number of digits to the right of the decimal point.
fill(): The fill method is used to set a character to fill in the blank space of a field.
By default,the unused positions of the field are filled with white spaces.
The use of fill() to fill the unused positions by any desired character.
cout.fill(ch);
Where ch represents the character which is used for filling the unused positions.
Example:
OUTPUT:
* * 1 2 3
cout.fill(‘*’);
cout.width(5);
cout<<123;
setf(): The setf method is used to set various flags for formatting output.
The function setf() sets the iostream format flags of the current stream to flags. The
optional needed argument specifies that only the flags that are in both flags and needed should be
set. The return value is the previous configuration of iostream format flags.
cout.setf(arg1,arg2);
where arg1 is one of the formatting flags defined in the class ios. The formatting flag specifies the
format action required for the output.
arg2 represents as bit field specifies the group to which the formatting flag belongs.
Where set bits is one of the flags defined in the class ios. It specifies the format action required for
the output, and field specifies the group to which the formatting flag belongs. Both the forms
return the previous settings. The flags, bit-fields when set with setf() and their actions is shown in
table.
The following table shows that some of flag value without bit fields for the setf function.
example:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
cout << "Example for formatted IO" << endl;
cout << "Default: " << endl;
cout << 123 << endl;
cout.precision(5);
cout << "precision(5) ---> " << 123.4567890 << endl;
cout << "precision(5) ---> " << 9.876543210 << endl;
return 0;
}
Function Description
setw(int) Used to set the width in number of characters for the immediate
output data.
setfill(char) Used to fill the blank spaces in output with given character.
The iomanip.h also contains the following format flags using in formatted IO in C++.
Flag Description
endl Used to move the cursor position to a newline.
ends Used to print a blank space (null character).
dec Used to set the decimal flag.
oct Used to set the octal flag.
hex Used to set the hexadecimal flag.
left Used to set the left alignment flag.
Flag Description
right Used to set the right alignment flag.
showbase Used to set the showbase flag.
noshowbase Used to set the noshowbase flag.
showpos Used to set the showpos flag.
noshowpos Used to set the noshowpos flag.
showpoit Used to set the showpoit flag.
noshowpoint Used to set the noshowpoint flag.
File streams:-
• A file is a collection of related data stored in a particular area on the disk.
• Programs can be designed to perform the read and write operations on these files.
• In general a file is a sequence of bits, bytes, lines or records whose meaning is defined by its
user.
• In C++, file input/output facilities are implemented through a header file fstream.h.
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:
Data Description
Type
fstream It is used to create files, write information to files, and read information
from files.
1. ios:-
3. ostream:-
• 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 support for simultaneous input and output operations.
• Inherits all the functions from istream and ostream classes through iostream.
9. filebuf:-
S.
No. Text file Binary File
S.
No. Text file Binary File
It stores data using ASCII format i.e. It stores data in binary format i.e. with the
2. human-readable graphic characters. help of 0 and 1.
4. These files create portability problems. These files are easily portable.
Error in a textual file can be easily Error in a binary file corrupts the file and is
7. recognized and eliminated. not easily detected.
In a text file, a new line character is first In binary file, no such conversion from
8.
converted to a carriage return-line feed newline to carriage return-line feed
S.
No. Text file Binary File
Text files are used to store data more user Binary files are used to store data more
10. friendly. compactly.
• The syntax of opening a file for output purpose only using an object ofstream class and the
constructor is as follows:
ofstream ofstream_object(“file name”);
Example: ofstream fout (“results.dat”);
Where fout is declared as an object of ofstream type and it is opened result.dat file for output
purpose.
• The syntax of opening a file for input purpose only using an object ifstream class and the
constructor is as follows:
ifstream ifstream_object(“file name”);
Example: ifstream fin (“results.dat”);
Where fin is declared as an object of ifstream type and it is opened result.dat file for input
purpose.
File Modes:
While using constructors or open( ), the files were created or opened in the default mode.
There was only one argument passed, i.e. the filename. C++ provides a mechanism of opening a file
in different modes in which case the second parameter must be explicitly passed.
Syntax:
stream_object.open(“filename”, mode);
Example: fout.open(“data”, ios::app) // This opens the file data in the append mode.
The lists of file modes are:
Example:
fstreamfout (“text”, ios::out); // open text in output mode
fstream fin(“text”, ios::in); // open text in input mode
fout.open(“data”, ios::app) // This opens the file data in the append mode
fout.open(“data”, ios::app | ios::nocreate) // This opens the file in the append mode but fails
to open if it does not exist
• The mode can be combine two or more parameter using the bitwise OR operator( | )
Example: fout.open(“data”,ios::app|ios::nocreate);
Closing File:
• Opening a file eshtablishes the linkage between a stream object and an operating system file.
• After the intended operations are done with the file then we removes the linage between the
file and the stream object
• The member function close( ) on its execution removes the linkage between the file and the
stream object.
• After close the file; the file should be safely saved on the secondary storage in the memory.
Syntax: stream_object.close( );
Example: ofstream.close( );
ifstream.close( );
• The put( ) member function belongs to the class ofstream and writes single character to the
associated stream.
Syntax: ofstream_object.put(ch); // where ch is the character variable.
Example: char ch=’A’;
ofstream fout(“text.txt”);
fout.put (ch);
• fout is the object of ofstream. Text is the name of the file. Value at ch is written to text.
get( ):
• The get( ) member function belong to the class ifstream and reads a single character from the
associated stream.
Syntax: ifstream_object.get (ch); // where ch is the character variable.
Example: char ch;
ifstream fin(“text.txt”);
fin.get (ch);
• fin is the object of ifstream. Text is the name of the file. Reads a character into the variable
ch.
getline( ):
• The write ( ) member function belongs to the class ofstream and which is used to write
binary data to a file.
Syntax: ofstream_object.write((char *) & variable, sizeof(variable));
• These functions take 2 arguments. The first is the address of the variable and second the size
of the variable in bytes. The address of the variable must be type casted to pointer to
character.
Example: student s;
ofstream fout(“std.dat”, ios::binary);
fout.write((char *) &s, sizeof(s));
read ( ):
• The read ( ) member function belongs to the class ifstream and which is used to read binary
data from a file.
Syntax: ifstream_object.read((char *) & variable, sizeof(variable));
These functions take 2 arguments. The first is the address of the variable and second
the size of the variable in bytes. The address of the variable must be type casted to pointer to
character.
Example: student s;
ifstream fin(“std.dat”, ios::binary);
fin.write((char *) &s, sizeof(s));
• It returns a non-zero (true) value if the end of file condition is encountered while reading;
otherwise returns a zero (false).
• Example:
ifstream fin;
if(fin.eof( ))
{
statements;
}
This is used to execute set statements on reaching the end of the file by the object fin.
• When we open a file in read only mode, the input pointer is automatically set to the first byte
as 0 at the beginning so that we read the file from the beginning.
• When we open a file in write only mode, the existing contents are deleted and output pointer
is set at the beginning
• If we want to open an existing file to add more data, the file is opened in append mode. This
moves the file pointer to the end of the file, so that we write new data from that location.
• Move the get pointer to a specified location from the beginning of a file.
There are two types:
▪ seekg(long);
▪ seekg(offset, seekdir);
• The seekg(long) moves the get pointer to a specified location from the beginning of a file.
Example: inf.seekg(20);
seekp ( ):
• Move the put pointer to a specified location from the beginning of a file.
There are two types:
▪ seekp(long);
▪ seekp(offset, seekdir);
• The seekp(long) moves the put pointer to a specified location from the beginning of a file.
Example: inf.seekp(20);
fail( ) It returns a non-zero (true) value when an input or output operation has failed.
good() It returns a non-zero (true) value when no error has occurred; otherwise returns zero
(false).
eof( ) It returns a non-zero (true) value when end-of-file is encountered while reading; otherwise
returns zero (false).
clear()-this function used to reset the error statethen we attempt further operation.