Professional Documents
Culture Documents
Module 5
Concept of streams: cin and cout objects
C++ stream classes, Unformatted and
formatted I/O, manipulators,
File stream: C++ File stream classes, File
management functions, File modes, Binary
and random Files
Console I/O Operations
• A program is a set of instructions that facilitates
problem solving.
• Every program must go through the process of
input-compute-output flow so that it can take some
data as input and generate processed data as O/P.
• So there should be a mechanism which supplies
input to the program and present the processed
data.
3
Stream
• C++ I/O system is capable of working with a variety of
devices such as, terminals, disks, tape drivers etc.
• Stream is a common interface independent of physical
devices.
• Stream flow of data
• Different streams are used to represent different kinds of
data flow
• Each stream is associated with a particular class which
contains member functions and definitions for dealing with
that particular kind of data flow
4
Stream
Input stream
Output stream
5
Stream
6
Stream classes
• C++ I/O library provides a hierarchy of classes used to
define various streams that help to handle console I/O and
File I/O operations.
• A stream in C++ is represented using an object of a
particular stream class.
• For example cin is the input stream object that represents
the input stream connected to standard input device.
• cout is the is the output stream object that represents the
input stream connected to standard output device.
7
Stream classes
8
Stream Class: ios
• A base class for the hierarchy of stream classes
• Contains basic facilities that are used by all other input and
output classes.
9
Stream Class: istream
• An input stream class
10
Stream Class: ostream
• An output stream class
11
Stream Class: iostream
• An input/output stream class
12
Stream Class
13
Predefined Objects
• When a C++ program begins execution, four built-in streams
are automatically opened.
14
Classification of I/O operations
• Streams defined in console I/O headers enable to perform
two types of I/O operations:
formatted I/O
unformatted I/O
15
Unformatted I/O operations
• Unformatted console input/output functions are used for
performing input/output operations at console and the resulting
data is left unformatted and untransformed it is left in its raw
and original form.
• Unformatted I/O operations are the functions that do not exclude
whitespaces.
• No character interpretation takes place in this operation.
• Such I/O functions defined in the iostream class are get(), put(),
getline() and write().
16
Unformatted I/O operations
• Overloaded operator >> (extraction operator)
• It is overloaded in the istream class
Syntax:
• cin>>var1>>var2>>var3>>….>>varN
• Var1,var2.. Are valid C++ variable names.
• This statement will cause the computer to stop execution and
look for input data from standard input device
• The operator >> reads the data character by character and
reading will be terminated at the encounter of a white space
or a character of a different data type
17
Unformatted I/O operations
• Overloaded << (insertion operator)
• Syntax(<<)
• cout<<item1<<item2<<….<<itemN
18
Unformatted I/O operations
19
Unformatted I/O operations
• get() Function
• The get() member function of istream class extracts
unformatted data from the stream and is similar to
operator>>.However, get() includes whitespaces.
• The get() function is used to extract single character
• 2 types of get() functions
– get(char *) Assigns input character to its argument
– get(void) returns the input character
Since it is a member function of istream class it should be
invoked using cin
20
Unformatted I/O operations
• put() Function
• The put() member function of ostream writes a single
character to associated o/p stream and returns the
reference to that stream object.
• Since it is a member function of ostream class it should be
invoked using cout
• Syntax
• put(char ch)
21
Unformatted I/O operations
22
Unformatted I/O operations
• getline() Function
• The getline() function is also a member function of the
istream class
• It reads a whole line of text that ends with a newline
character
• Invoked using the object cin
• Syntax
cin.getline(character array,size);
Reading is terminated as soon as either the new line or at
size-1
23
Unformatted I/O operations
24
Unformatted I/O operations
25
Formatted I/O operations
• Formatted console input/output functions are used for
performing input/output operations at console and the
resulting data is formatted and transformed.
Manipulators
26
formatted I/O operations
27
Formatted I/O operations
Defining Field Width: width()
cout.width(w);
• w the field width(number of columns)
• The width() function can specify the field width for only one item
28
formatted I/O operations
29
Formatted I/O operations
Setting Precision: precision()
cout.precision(d);
30
Formatted I/O operations
Setting Precision: precision()
Cout.precison(3); Output
Cout<<sqrt(2)<<“\n|”; 1.141
3.142
Cout<<3.14159<<“\n”;
2.5
Cout<<2.50032<<“\n”;
31
Formatted I/O operations
Filling and padding: fill()
32
formatted I/O operations
33
Formatted I/O operations
Formatting Flags, Bit-fields and setf()
cout.setf(arg1,arg2);
• arg2 is bit field specifies the group to which the formatting flag
belongs
34
formatted I/O operations
35
formatted I/O operations
36
Formatted I/O operations
Formatting Flags without Bit-fields
37
Formatted I/O operations
Formatting Flags without Bit-fields
38
Formatted I/O operations
unsetf() function
cout.unsetf(arg);
39
Managing Output with Manipulators
• The data values can be formatted using manipulators.
• Manipulators are the special functions included in the
iomanip header.
• Since manipulators are simple functions and are not member
functions, they are used directly without using the object
name and dot operator along with the stream.
• Manipulators have similar functions as that of ios class
functions and flags.
• The manipulators can also be concatenated, which implies
that several manipulators can be used in a single cout
statement.
40
Managing Output with Manipulators
41
Managing Output with Manipulators
setprecision (int n)
• Example
• cout<<setprecision(4)<<3.55455;
42
Managing Output with Manipulators
setw(int n )
• This function is used to change the width of the field. The
data values are printed within the characters specified by n.
43
Managing Output with Manipulators
setfill(char ch)
• The set fill (), function fills the unused space of the field
width with specified characters
44
Managing Output with Manipulators
setiosflags() and resetiosflags()
• These functions also use the same flags defined by the ios
class.
45
Managing Output with Manipulators
setiosflags() and resetiosflags()
float n = 0.92;
cout<<n<<endl ;
cout<<setiosflags(ios::scientific)<<n<<endl;
cout<<resetiosflags(ios::scientific) <<n<<endl;
46
User defined manipulators
47
User defined manipulators
• Example
ostream & mystyle(ostream & c)
{
cout<<“My Style”;
cout<<setw(5)<<setprecision(2);
return(c);
}
Int main() 1 . 3 5
{
float a=1.34566;
cout<<mystyle<<a;
}
48
Disk I/O Operations
• Most of the real-life applications require large amounts of
input and output data to be handled that is difficult to
manage using the commonly used console input/output (I/O)
like keyboard and screen.
• Moreover, the output obtained using console I/O is not
permanent and is lost as soon as the program terminates.
• This necessitates the requirement of some devices such as
hard disk, magnetic tape or a floppy disk to store large
amount of data permanently.
• The data is stored in these devices in the form of files (also
known as disk files).
49
Files
• A file is a collection of related data stored on some
storage device.
• The data stored in is permanent and can easily be
accessed as and when required.
• Moreover, the data stored in a file by one program
can be accessed or modified by various programs as
per the requirements
50
File Streams
• A file stream refers to the flow of data between a
program and the files
• Depending on the flow of data from file or to file,
a stream can be classified into two types
Input stream: It reads the data from the file and
supplies it to the program.
Output stream: It receives data from the program and
writes it to the file.
51
File Streams
52
File Streams
• There are two modes by which data can be
transferred to and from streams
• text mode: A file which is opened in text mode is
known as text file
• binary mode :A file opened in binary mode is known
as binary file.
53
Text File Vs Binary File
Text File Binary File
Storage of data Stores data as a sequence of characters Stores data as a sequence of bytes
Handling data Some character translations take place while No such character translation takes
data is being read from or written to the file. place. Thus, the number of bytes
Hence, there is a possibility that the number of read (or written) is the same as that
characters written (or read) may not be the same in the file
as that in the file
Representation of end The end of file is represented by a special There is no such special character to
of file character detect the end of file. The end of
file is determined by keeping track
of the number of characters
present in the file.
54
File Stream Classes
• C++ provides different streams to represent different
kinds of data flow.
• Each stream is associated with a particular class, which
contains the member functions for reading from or
writing to the devices
• The classes specific to the disk file I/O operations are
known as file classes and are declared in the header
<fstream>.
• The header <fstream> define several classes, including
ifstream, ofstream and fstream, which are working with
files.
55
File Stream Classes
• These classes are derived from istream, ostream and
iostream respectively, which in turn are derived from
ios class.
• The file-specific classes can have access to all the
member functions of ios.
• In addition, the file-specific classes are also derived
from fstreambase class.
• The fstreambase class contains the object of class
filebuf, which also inherits member is of the class
streambuf.
56
File Stream Classes
57
File Stream Classes
ifstream:
• The ifstream is an input file stream class which
provides functions for performing reading operations
only.
• It contains functions such as get (), getline(), read (),
seekg () and tellg(), which are derived from istream
class.
58
File Stream Classes
ofstream:
• The ofstream is an output file stream class which
provides functions for performing writing operations
only.
• It contains functions such as put (), write(), seekp()
and tellp(), which are derived from ostream class
59
File Stream Classes
fstream:
• The fstream is an I/O file stream class and hence,
provides functions for performing input as well as
output operations.
• It contains all the functions of istream and ostream
classes, which are inherited through iostream class
60
File Stream Classes
fstreambase:
• The fstreambase class serves as a base class for
ifstream, ofstream and fstream classes.
• It contains open() and close() functions and also other
operations that are common to all file streams.
61
62
Opening and Closing A File
• To perform any operation on a file, it needs to be opened
first.
• A file is opened by linking it to a stream.
• Thus, for opening a file, an object of the particular stream
class is created first and then associated with the file
• A file can be opened in two ways, that is either by using the
constructor or the member function open() of the stream class
63
Opening a File Using The Constructor
64
Opening a File Using The Constructor
• Example
65
Closing A File
66
#include<iostream>
#include<fstream>
using namespace std; ifstream inf("FirstFile.txt");
int main() inf>>name;
{ inf>>cost;
ofstream outf("FirstFile.txt"); cout<<"itemname: "<<name<<endl;
cout<<"Cost: "<<cost;
cout<<"Enter item name:";
char name[30]; return 0;
cin>>name;
outf<<name<<endl; }
cout<<"Enter item cost:";
float cost;
cin>>cost;
outf<<cost<<endl;
outf.close();
67
Detecting End-of-file
• While reading data from the file, the end position of the file is required
to be detected
• When the end of file is encountered, a signal END-OF-FILE (EOF) is
sent to the program by the operating system.
• This signal can be detected by using the function eof(),which is a
member function of the ios class.
• Here, the function eof() returns zero as long as the end-of-file is not
reached. As soon as the end-of-file is reached, it evaluates to a non-
zero value and the loop terminates. 68
Detecting End-of-file
• The end-of-file condition can also be detected by testing the stream
object directly as
• In this loop, the value of file stream object is tested for any error
condition including end-of-file condition.
69
Opening A File Using OPEN ( ) Function
70
Opening A File Using open( ) Function
• Open() can be used to open multiple files that use the same stream
object
• The first file is closed before opening the second one Streams can
be connected to only one file at a time.
• Example:
ofstream outfile;
outfile.open(“data”);
outfile.close();
outfile.open(“data2”);
outfile.close();
71
Opening A File Using open( ) Function
int main() cout<<"country file:"<<endl;
{ char line[100];
while(fin)
ofstream fout;
{
fout.open("country.txt"); fin.getline(line,50);
fout<<"UK"<<endl; cout<<line<<endl;
fout<<"USA"<<endl; }
fout<<"India"<<endl; fin.close();
fin.open("capital.txt");
fout.close();
cout<<"capital file:"<<endl;
fout.open("capital.txt"); while(fin)
fout<<"Washington"<<endl; {
fout<<"London"<<endl; fin.getline(line,50);
fout<<"New Delhi"<<endl; cout<<line<<endl;
}
fout.close();
fin.close();
ifstream fin; }
fin.open("country.txt");
72
Copy the content of one file to another
#include<iostream> fout.open("Secondfile.txt");
#include<fstream> fin.open("Firstfile.txt");
while(fin)
using namespace std;
{
int main() fin.getline(s,20);
{ fout<<s<<"\n";
ofstream fout; }
ifstream fin; fin.close();
fout.close();
fout.open("Firstfile.txt");
fin.open("Secondfile.txt");
char s[20]; while(fin)
int i; {
for(i=1;i<=10;i++) fin.getline(s,20);
{ cout<<s<<endl;
}
fout<<"Number:"<<i<<"\n";
fin.close();
} }
fout.close();
73
Program to count the number of lines
74
Specifying File Modes
• Open() function can take 2 arguments : one argument is the file name
and the second is for specifying the file mode(file mode parameter)
• The file mode describes how a file is to be used, that is, to read from
it, to write to it, to append to it and so on.
75
Specifying File Modes
76
Specifying File Modes
• The default mode for the ifstream class is ios::in, for ofstream class is
ios::out and for fstream class ios::in | ios::out. Thus in the absence of
this argument, the default value is provided.
• infile.open(“marks”);
• infile.open(“marks”,ios::in);
77
Specifying File Modes
• Opening a file in the ios::out mode also opens it in the ios::trunc mode.
Hence, an object of the of stream class is directly opened in the
ios::out | ios::trunc mode by default.
• A file name can include a path specifier. However, if the path is not
specified, the compiler assumes the tile to be present in the current
directory.
• Two or more file modes can be combined using the bitwise OR operator ( | )
78
File Pointers
• In C++, every file is associated with two file pointers
• These file pointers represents integer values that specify the current position
(byte number) in the file from where writing and reading will start.
• get pointer specifies the position from where the next read operation will
start
• put pointer specifies the position from where the next write operation will
start.
79
File Pointers
80
Manipulation of File Pointers
• Each time a read or write operation is performed, the appropriate pointer
is automatically advanced sequentially in the file.
81
Manipulation of File Pointers
82
Manipulation of File Pointers
Example 1:
83
Manipulation of File Pointers
Example 2:
84
Manipulation of File Pointers
• The get pointer can be moved to the desired position by specifying the
positive value of pos_type in the function seekg() as an argument.
• However, the get pointer can also be moved to the desired position using
an offset value (can be positive or negative) relative to one of the three
specific positions in the file.
85
Manipulation of File Pointers
86
Sequential Input Output operations
87
Reading and Writing Files
• However, the operators << and >> are overloaded to work in the same way
with file stream objects.
• The only difference is that instead of using cout and cin, a stream object
linked to a file is used.
88
Reading and Writing Files
• The functions put () and get (), which are the member functions of classes
ostream and istream respectively, are used to write and read a single
character at a time from the linked stream.
• The get() function reads a single character from the associated stream
89
get() and put() functions
# include<fstream> outfile.close();
#include<iostream> ifstream infile("newtext1.txt");
#include<cstring> char ch;
using namespace std; while(infile)
{
int main()
infile.get(ch);
{ cout<<ch;
ofstream outfile("newtext1.txt"); }
char str[ ]="using get() & put()"; infile.close();
int len=strlen(str); return 0;
}
for(int i=0;i<len;i++)
outfile.put(str[i]);
90
Reading and Writing Files
91
Reading /Writing Object using read() and write()
92
Reading /Writing Object using read() and write()
93
Reading and writing class object
class book int main()
{ { book b1;
char title[30];int price; b1.getdata();
ofstream fout;
public: fout.open("Newfile1.txt");
void getdata() fout.write((char*)&b1,sizeof(b1));
{ cout<<"Enter the title:"; fout.close();
cin>>title; ifstream fin;
cout<<"Enter price"; fin.open("Newfile1.txt");
fin.read((char*)&b1,sizeof(b1));
cin>>price; fin.close();
} b1.display();
void display()
{ cout<<"Title:"<<title<<endl; }
cout<<"Price:"<<price;
}
};
94
Reading and writing class object
class check
{
char name[20];
int m1,m2,m3,tot;
public:
void getdata()
{
cout<<"Enter name and 3 marks";
cin>>name>>m1>>m2>>m3;
}
void putdata()
{
cout<<"\n"<<name<<:"<<setw(3)<<m1<<setw(3)<<m2<<m3;
}
};
95
int main()
{
check c[20];int i,n;
cout<<"enter limit ";cin>>n;
ofstream ofile(“file1.txt");
for(i=0;i<n;i++)
{
c[i].getdata();
ofile.write((char*)& c[i],sizeof(c[i]));
}
ofile.close();
ifstream ifile(“file1.txt");
for(i=0;i<n;i++)
{
ifile.read((char *) & c[i],sizeof(c[i]));
c[i].putdata();
}
ifile.close(); 96
University Question Paper
1. Differentiate between binary and random files.
7. How files are implemented in C++. Explain with a sample program to read and write objects using file.
10. Discuss about file streams. Discuss about file management functions.
11. Explain file objects. Write a sample program to read and print file objects.
97