You are on page 1of 97

I/O and File Management

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

In input operations, the bytes are transferred from a device to


the main memory

Output stream

The bytes are transferred from main memory to a device such


as (display screen, printer, disk, n/w…)

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

• Declared as a virtual base class for istream and ostream


classes

• Contains basic facilities that are used by all other input and
output classes.

• Keeps track of the format and error state information for


derived classes.

9
Stream Class: istream
• An input stream class

• Inherits the properties and behavior of ios class

• Contains overloaded extraction operator (>>)

• Comprises istream objects to extract input from the stream

• Also contains input functions such as get(),getline () and


read()

10
Stream Class: ostream
• An output stream class

• Inherits the properties and behaviour of ios class

• Contains the insertion operator (<<)

• Comprises the ostream object to insert output into the


stream

• Facilitates formatted as well as unformatted output

• Declared output functions such as put() and write()

11
Stream Class: iostream
• An input/output stream class

• Inherits the properties from istream and ostream through


multiple inheritance

• Contains all the input and output functions

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)

• It is overloaded in the ostream class

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

• C++ supports a number of features that could be used for


formatting the output
ios class functions and flags

Manipulators

User defined functions

26
formatted I/O operations

27
Formatted I/O operations
Defining Field Width: width()

• Using this function, we can specify the width of a value to


be displayed in the output at the console.

cout.width(w);
• w the field width(number of columns)

• The output will be printed in a field of w characters wide at the right


end of the field

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

• Using this function, we can specify the number of digits to


the right of decimal, to be printed in the output at the
console.

cout.precision(d);

• d the number of digits to the right of the decimal point

• Precision() retains the setting in effect until it is reset

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

• Using this function, we can fill the unused white spaces in a


value(to be printed at the console), with a character of our
choice
cout.fill(ch);
• ch represents the character which is used for filling the unused
positions

• It stays in effect till we change it

32
formatted I/O operations

33
Formatted I/O operations
Formatting Flags, Bit-fields and setf()

• Using this function, we can set the flags, which allow us to


display a value in a particular format.

cout.setf(arg1,arg2);

• arg 1 is one of the formatting flags in the class ios

• 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

• The flag set by setf() function can be cleared using the


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)

• This function is used to set the number of digits to be


printed for the floating point data values.

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

• The setiosflags() and resetiosflags() functions are used to set


or reset the flags which control the output stream format.

• 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

• The user defined manipulators are defined as follows:

ostream & manipulator(ostream & ostr)


{
set of statements;
return ostr;
}

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

• When a file is opened using the constructor of a stream class,


the file name is passed to it as an argument.
• Thus, the constructor initializes the stream object with the
file name passed to it
• Syntax

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.

• As soon as the end-of-file is reached or any other error occurs, object


returns zero and the loop terminates

69
Opening A File Using OPEN ( ) Function

• The function open(), is a member function of the fstreambase class


• The creation of stream object and its linking with a particular file
using the open() function are performed in separate statements.

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 prototype of both the constructor and open() function contain


default mode for each type of stream.

• 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

• get pointer (input pointer)

• put pointer (output pointer)

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

• However, in some cases a file is required to be read from or written to


any other position rather than its default position.(adding or updating
records in an existing file) the file pointers must be moved to the
desired location explicitly by the programmer.

• In C++ manipulation of pointers can be accomplished through functions like


tellg(), seekg() belonging to ifstream class and tellp() & seekp() belonging
to ofstream class

81
Manipulation of File Pointers

82
Manipulation of File Pointers
Example 1:

• ofstream outfile(“myfile”,ios::app);  put pointer will be at the end of


the file.

• int cur_pos=outfile.tellp(); returns the current position of put


pointer number of bytes in the file

83
Manipulation of File Pointers
Example 2:

• ifstream infile(“myfile”);  get pointer will be at the start position

• Infile.seekg(10); moves the file pointer to the (10+1)th byte

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.

• This positive value represents the absolute position in the file.

• 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

• The file stream classes support a number of member


functions for performing the input and output operations in
file

• using >> and << operators


• using get() and put()
• using read() and write()

87
Reading and Writing Files

using >> and << operators


• The insertion operator (<<) and extraction operator (>>) have been used
with the standard stream objects cout and cin respectively.

• 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

using get() and put()

• 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

• put() function writes a character to the stream.

• Both the functions return a reference to the 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

using read() and write()


• The functions read() and write(), also known as binary I/O functions are used
to handle blocks of binary data.
• Functions read() and write() operate on binary values and not on text, that is,
they treat data as a sequence of bytes.
• Both these functions can read and write an entire structure (array, structure
variable or a class object) in one I/O operation.
• Hence, the data members are not required to be read or written separately.

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.

2. Explain about file modes

3. Describe two methods of opening file.

4. Discuss about file pointers.

5. Differentiate between formatted I/O and unformatted I/O.

6. Write a note on C++ Streams

7. How files are implemented in C++. Explain with a sample program to read and write objects using file.

8. How are files implemented in C++? Explain with a sample program.

9. Write a c++ program to read and display an object 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

You might also like