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

Input/output Streams and Files: Sushant Bhattarai

Input

Uploaded by

Sailesh Sailesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Input/output Streams and Files: Sushant Bhattarai

Input

Uploaded by

Sailesh Sailesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 86

8.

Input/output Streams
and Files

Sushant Bhattarai
Stream Based input/output

 The input data can be read from input devices


like keyboard or data files.
 The output data can be displayed in screen or
written in a data file.
 This is called input/output process.
 C++ I/O implements concept of streams, which
are sequence of bytes.
 There are two kind of streams.
1)Input Stream
2) output stream
Stream Based input/output

1) Input Stream- It is the flow of data bytes from a


device to main memory.
2) Output Stream - It is the flow of data bytes from
main memory to a device.
8.1 Input/output Stream
Class Hierarchy

Er.Sushant Bhattarai
Stream Classes and
their Hierarchy
 C++ has a number of stream classes for
performing I/O operations.
 Different streams are used to represent
different kinds of data flow.

Stream Classes and
their Hierarchy
Stream Classes and
their Hierarchy
 The ios class is base class of all stream classes
and contains most of stream features.
1. ios : It is the base class for other stream classes.
2. istream: It is the child class of ios and has i/p
related functions, data, constants and operators.
3. ostream: It is the child class of ios
Stream Classes and
their Hierarchy
4) fstreambase : It is the base class for fstream
5) fstream : It provides facility for i/o operations,
6) ifstream : It provides i/p operations on file.
7) iostream : It provides both i/o operations.
8) ofstream
8.2 Unformatted
Input/output

Er.Sushant Bhatta
Unformatted I/O

 Unformatted operations do not allow user


to read or display data in desired format.
 The unformatted operations supported by
C++ are:
1.Overloaded operators >> and <<
2.put() and get() functions
3.getline
1. Overloaded operators
>> and <<

 The insertion operator(<<) and extraction


operator(>>) are overloaded operators which are
used for reading/writing data from/to i/o devices.
 The predefined object cout is an object of
ostream class which is used with << operator.

1. Overloaded operators
>> and <<

 Similarly, the predefined object cin is an


instance/object of istream class which is used
with >> operator.

2. put() and get() functions

 The class istream defines the member


function get() and ostream defines put() for
single character I/O operation.
 Syntax:
cin.get(char_variable);
cout.put(char_variable or char_constant
2. put() and get() functions
2. put() and get() functions
3. getline() and write()
functions

 The getline() function takes whole line of text that ends


with a newline character(return/enter) key.
cin.getline(string_variable,size);
 The reading process is terminated as soon as either the
newline character ‘\n’ is encountered or size-1 characters
are read.
 Remember extraction operator(>>) with cin object
doesn’t support the white space but getline
3. getline() and write()
functions

 Similarly, write() function displays an entire line


and has the following form
cout.write(string,size);
string represents the name of the string
size indicates the number of character to be
displayed.
3. getline() and write()
functions
3. getline() and write()
functions
8.3 Formatted Input/output

Er.Sushant Bhatta
Formatted I/O

 Formatted operations allow the input read from the


keyboard or the output displayed on screen to be
formatted according to our requirements.
ios Stream Class Member
Functions and Flags

 The ios class contains a large number of


member functions that would help us to
format the output in a number of ways
a)width()
The member function width() is used to
define necessary field width for output of
data item.
cout.width(w)
w is the field width(number of columns)
ios Stream Class Member
Functions and Flags

a) width()
ios Stream Class Member
Functions and Flags

a) width()
ios Stream Class Member
Functions and Flags

b) precision()
 The default precision of float type
numbers is six.
 cout.precision
ios Stream Class Member
Functions and Flags

b) precision()
ios Stream Class Member
Functions and Flags

b) precision()
Standard Manipulators

c) setf() : This is used to set various flags used for


formatting text in C++.
cout.setf(argument1, argument2)
argument1 is one of the formatting flags defined in
the class ios.
Standard Manipulators

c)setf()
Description of Format Flags Bit field
Left justified output ios::left ios::adjusted
Right justified output ios::right ios::adjusted
Padding after sign ios::internal ios::adjusted
Scientific notation ios::scientific ios::floatfield
Fixed point notation ios::fixed ios::floatfield

Decimal base ios:: dec ios:: basefield


Octal base ios::oct ios:: basefield
Hexadcimal base ios::hex ios:: basefield
Standard Manipulators

c)setf()
Standard Manipulators

c)setf()
Standard Manipulators

c)unsetf()
 It is also a member of ios class which is
used to clear the flag specified
Standard Manipulators

c)unsetf()
Standard Manipulators

c)unsetf()
User Defined Manipulators

 We can also define our own manipulator


according to the requirements of the
program.
ostream &manipulator_name(ostream & o)
{
statement1;
statement2;
return o;
User Defined Manipulators
User Defined Manipulators
8.4 File I/O with Streams

Sushant Bhattarai
File I/O

 A file is a collection of data stored in a


particular location on the disk.
 A file has specific extension
like .doc, .ppt, .xls etc.
 There are two types of file in C++
1.Sequential Files  where data are stored
sequentially.
2.Random Access Files where data can
be extracted randomly
File I/O

 The I/O stream of files reads/writes data


from/to files.

8.5 File Stream Class
Hierarchy

Er.Sushant Bhatta
Classes for Operations
with Files
 The main classes are
1. ifstream  if we want to read data from file, we
create object or file stream of ifstream class.
2. ofstream  if we want to write data to a file, we
create object or file stream of ofstream class.
3. fstream  if both operations is needed we create
object of the file stream of fstream
8.6 Operations on Files

Er.Sushant Bhatta
Steps in Processing
File
 When we use file in computer system for
reading and writing purpose, we have to
perform some activities.
 C++ uses the following steps
1.Opening a File.
2.Operation on a File.
3. Close the file
8.7 ASCII and Binary Files

Er.Sushant Bhatta
ASCII Files

 An ASCII file is a text file in which each


byte represents one character according to
the ASCII code.
Binary Files

 Binary files are non-text file.


 They are usually thought of as being a
sequence of bytes.
 Compiled program are typical examples.
8.8 Opening File, File
Modes and Closing Files

Er.Sushant Bhatta
Opening and Closing a
File
 Before we read/write from/to a file we must open it.
 It is the process of establishing a link between program
and OS.
 In C++, we can open a file in two methods.
1. Using constructor of File-related stream class.
2. Using member function open() of stream class.
• When I/O operations on a file are completed, we shall
close it so that it’s resources become available to the
system again. We have to call the stream class member
function close().
stream_object.close()
Using constructor of File-related stream
class.

 A constructor of ifstream, ofstream or


fstream class can be used to create a
stream object and initialize their data
members and open a file.
 The filename is passed as argument.
 The class of ofstream is used to create
output stream, ifstream is used to create
input stream and fstream is used to create
both input and output stream object
Using constructor of File-related stream
class.

Syntax:
stream_class stream_object(filename,mode)
 Where filename is the name of file to be opened and
mode is an optional parameter which might include
1)ios::in  I/P mode.
2)ios::out  O/P mode.
3)ios::app  append mode.
4)ios::binary  binary mode.
5)ios::ate opens a file and set intial
Using constructor of File-related stream
class.

6)ios::trunc  if already existing file is opened for I/O, its


previous content is deleted and replaced by a new one.
7)ios::nocreate Open fails if specified file doesn’t exists.
8) ios::noreplace  Opens existing file without replacing it.
Note:  ios::app and ios::ate look similar but ios::ate is
more versatile as it allows to add or modify existing data
anywhere in the file by changing file pointer .
Also, all of this flag can be combined using bitwise ‘OR” ( | ).
Eg:
ofstream myfile(“test.txt”, ios::out | ios::app | ios
Using constructor of File-related stream
class.

E.g.
ofstream out(“welcome.txt”);
ifstream in(“hello.txt”);
fstream in_out(“myfile.txt”,ios::in || ios::out);
Using constructor of File-related stream
class.

A program to write “I am Alan” in a file named apple.txt


using object of ofstream
Using constructor of File-related stream
class.

A program to write “I am Alan” in a file named apple.txt


using object of fstream class.
Example

 Write a program to read name, address


and phone number of your friend in a file
named phone.txt
Example

 Write a program to read name, address


and phone number of your friend in a file
named phone.txt
Another Example

 Write a program to read the name, roll and


marks of a student in 5 subject from a file
named marks.txt and calculate percentage.
Output
Using member function open() of
stream class.

 File can also be opened by using a


member function called open() of ifstream,
ofstream and fstream class.
File_Stream_Class Object_Name
Object_Name.open(“FileName,Mode);
Using member function open() of
stream class.

 E.g.
ofstream out
out.open(“apple.txt”)
out.close()

ifstream in
in.open(“apple.txt”)
in.close()

fstream o
o.open(“apple.txt”,ios::out)
o.close()
Using member function open() of
stream class.

Write C++ program to write the name,address and


phone number of your friend in a file named
friend.txt
Detecting End of file

 We can either use an object of ifstream


class which returns 0 when EOF is
encountered,
 Or, we can use eof() function of the ios
class which returns a non-zero value on
reaching the end of the file and zero
otherwise.
Detecting End of file

1. An object of ifstream class


while(ifstream_object)
{

Detecting End of file

1. An object of ifstream class


Detecting End of file
1. An object of ifstream class
Detecting End of file
2. eof() function of ios class.
while(object.eof()==0)
{
….
Detecting End of file
2. eof() function of ios class.
8.9 File Read/Write Using Stream
and Using Read & Write Function

Er.Sushant Bhatta
Reading/Writing from/to file using
read() and write()

 These functions handle the data in binary format i.e. the


values are stored in the disk file in the same format in
which they are stored in internal memory.
infile.read((char*) & V,sizeof(V));
outfile.write((char*) & V,sizeof(V));
Here, first argument is the address of variable V and the
second is length of that variable in bytes.
Reading/Writing from/to file using
read() and write()

Write a program to create a class named


person with data members: name, age,
gender and address. Read record of a
person using object of the class and write
the information to a file named person.txt
Reading/Writing from/to file using
read() and write()

Write a program to create a class named


person with data members: name, age,
gender and address. Read record of a
person using object of the class and write
the information to a file named person.txt
Reading/Writing from/to file using
read() and write()

Write a program to read from the above


created file and display result.
Reading/Writing from/to file using
read() and write()

Write a program to read from the above


created file and display result.
8.10 File pointers and their
Manipulators

Er.Sushant Bhatta
Direct/Random Access
in a File
 Sometimes we might want random access in a
file.
 We can access a particular data item placed in
any location without starting from the beginning.
 This is called random access.
 For random access, we need concept of
pointers.
 There are two types of file pointers: get pointer
and put pointer
File Pointers: get pointer and
put pointer

 The get and put pointer are used to move


cursor through the files while reading or writing.
 When a file is opened in read only mode, the get
pointer is automatically set to the beginning of
the file.
 When a file is opened in write mode, existing
contents are deleted and the put pointer is
automatically set to the beginning of the file.
 When a file is opened in append mode, the put
pointer is set at the end if the file and the data is
written to file from the end of file
File Pointers: get pointer and
put pointer

 We can use seekg(),seekp(),tellg() and tellp() functions


for the manipulations of these pointers.
1) seekg()
 It is a member function of istream class and is used to
move the get pointer to a specified location and reading
will start from that position.
 stream_object.seekg(offset,ref_position)
 offset specifies number of bytes the file is to moved from
the location specified by ref_position which are:
 ios::beg –we can also use 0/beginning of the file
 ios::cur –we can also use 1/current position of the file
 ios::end-we can also use 2/end of the file
File Pointers: get pointer and
put pointer

1) seekg()
E.g.
seekg(10,ios::beg)
seekg(10,ios::cur)
seekg(-5,ios::end)
seekg(0,ios::end)
Seekg(0,ios::beg);
File Pointers: get pointer and
put pointer

2) seekp()
 It is a member function of ostream class and it moves put pointer
to a specified position.
stream_object.seekp(offset,ref_position)

3) tellg()
 This is the member function of istream class and it gives or returns
the curent position of the get pointer.
int_variable = stream_object.tellg();

4)tellp()
This is a member function of ostream class and it gives or returns the
current position of the put pointer.
int_variable = stream_object.tellp();
File Pointers: get pointer and
put pointer

Write a program to show the use of tellg() and


seekg
File Pointers: get pointer and
put pointer

Write a program to show the use of tellg() and


seekg
File Pointers: get pointer and
put pointer

Write a program to show the use of tellp() and


seekp
File Pointers: get pointer and
put pointer

Write a program to show the use of tellp() and


seekp
Review Questions

1) What do you mean by stream? Explain input


and output stream? [4+6]
2) Explain opening file, file modes and closing file
with suitable examples. [10]
3) Write a program to read name, address, roll
number and marks in five subject of a student
and store the information in a file named
student.txt.[10]

You might also like