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

unit 5

Uploaded by

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

unit 5

Uploaded by

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

Unit V

Managing Console I/O Operations: Introduction - C++ Streams – C++ Stream Classes –
Unformatted I/O Operations – Formatted Console I/O Operation – Managing output with
Manipulators.
Working with Files: Introduction – Classes for File Stream Operators – Opening and closing a File –
Detecting end-of-file _ File Pointers and their Manipulators – Sequential Input and Output
Operations – Error Handling during File Operations – Command –Line Arguments.
Introduction
The process of giving data to the programs and getting result from the programs is called I/O
operation.
Q.No.1 C++ STREAMS
The flow of data between programs and the user through I/O devices is called streams.
There are two types of streams.
i) Input stream
ii) Output Stream
The stream that supplies data to the programs is called input stream.
The stream that receives the data from the program is called output stream.

C++ Stream Classes

In C++ there are number of stream classes for doing input-output operations. All these classes are
defined in the file iostream.h. The above figure shows the hierarchy of these classes.
ios class---- is topmost class in the stream classes hierarchy. It is the base class for istream,
ostream, and streambuf class.
iostream class-- is derived from both istream and ostream classes.. The class istream is used for
input and ostream for the output.
Class ios is indirectly inherited to iostream class using istream and ostream.
istream_withassign,ostream_withassign and iostream_withassign classes are inherited from
istream,ostream and iostream respectively.

Q.No.2 UNFORMATTED I/O OPERATIONS


The unformatted I/O opertions available in c++ are,
i) cin and cout
ii) get() and put()
iii) getline() and write()
cin , get() and getline() are used for input operation and cout, put() and putline() are used for
output operation.
Input Operation:
i) cin object
it is used to input data from the keyboard. It uses >>(extraction operator)to input data.
Syntax:
cin>>var1>>var2…….varn;
Examples:
int x,y;
cin>>x>>y;
ii) get()
It is a member function of istream class.This function is used to input a single
character.There are two types of get() function
a) get(char)
b) get(void)
a) get(char)
This function gets a single character from the input device and assigns it to the variable.
Syntax:
cin.get(variablename)
example:
char a;
cin.get(a);
b)get(void)
This function gets a single character from the input device and assigns it to the variable on
the left hand side..
Syntax:
Variablename=cin.get()
example:
char a;
a=cin.get();
iii) getline()
This function is used to read a line of text from the input device and assigns it to the
variable.
Syntax:
cin.getline(variablename size)
example:
char a[20];
cin.getline(a,20);
Output Operations:
i) cout object
it is used to display output on the screen. It uses <<(insertion operator)to input data.
Syntax:
cout<<var1<<var2…….varn;
Examples:
int x=10,y=20;
cout>>x>>y;
ii) put()
It is a member function of ostream class.This function is used to display a single
character.
Syntax:
cout.put(variablename);
example:
char a=’z’;
cout.put(a);
iii)write()
This function is used to display a line of text on the screen.
Syntax:
cout.write(variablename,size)
Size---number of characters to display
example:
char a[20]=”welcome”;
cout.write(a,7);
Q.No.3 FORMATTED CONSOLE I/O OPERATION
In c++,number of functions are available to format the output.These functions are available
in ios class. They are
i) width()
ii) precision()
iii) fill()
iv) setf()
v)unsetf()
i) width()
It is used to set the display width of an output value.
Syntax:
cout.width(w);
Example:
int a=8;
cout.width(5);
cout<<a;
The output is,
8
ii) precision()
It is used to specify the number of digits to be displayed after the decimal point of a float
value. By default, the floating numbers are displayed with 6 digits after the decimal point.
Syntax:
cout.precision(size);
Example:
float a =12.3421345;
cout.precision(3);
cout<<b;
The output is:
1 2 . 3 4 2

iii) fill()
This function is used to fill the unused positions with the specified character. By default,
unused positions are filled with white spaces.
Syntax:
cout.fill(character);
Example:
int a=8;
cout.width(5);
cout.fill(‘@’)
cout<<a;
The output is,
@ @ @ @ 8
iv) setf()
It is used to set flags. Using this, we can display the numbers
* with various alignments
* in scientific and fixed form
* in decimal, octal and hexa decimal.
Syntax:
cout.setf(arg1,arg2);
arg1—flag to set
arg2---bit-field
Flag Bit-Field Used for
ios::left ios::adjustfield Left justified output
ios::right ios::adjustfield Right justified output
ios::internal ios::adjustfield Adding character like *,$ after sign
ios::scientific ios::floatfield Scientific notation
ios::fixed ios::floatfield Fixed point form
ios:: ios::basefield Decimal base
ios::oct ios::basefield Octal base
ios::hex ios::basefield Hexa decimal base

Example:
int a=-8;
cout.width(5);
cout.fill(‘@’)
cout.setf(ios::internal,ios::adjustfield);
cout<<a;
The output is,
- @ @ @ 8
Fig: Flags that do not have bit fields
float a =12.34;
cout.precision(3);
cout.width(5);
cout.setf(ios::showpos);
cout.setf(ios::showpoint);
cout<<b;
output:
+12.340
v)unsetf()
It is used to clear the flags set by the various formatting function.
Syntax:
cout.unsetf();
Q.No.4 MANAGING OUTPUT WITH MANIPULATORS
The header file iomanip provides a set of functions called manipulators which can be used to
format the output.
Manipulator meaning
setw(int w) Set the field width to ‘w’
setprecision(int d) Set the floating point precision to ‘d’
setfill(int c) Set the fill character to ‘c’
setiosflags(long l) Set the format flag f
sesetiosflags(long l) Clear the flag
endl Insert new line
Example:
int a=8;
cout<<setw(5);
cout<<setfill(‘@’)
cout<<a;
The output is,
@ @ @ @ 8
DESIGNING OUR OWN MANIPULATOR
We can design our own manipulator for certain special purposes.
Syntax:
ostream & manipulator(ostream & output)
{
Statements
return(output)
}
Example:
#include<iostream.h>
ostream &rupees(ostream &stream)
{
stream<<”Rs”;
stream.precision(2);
stream.setf(ios::showpoint);
return(stream)
}
void main()
{
cout<<rupees<<112.5;
getch();
}
Output:
Rs.112.50
WORKING WITH FILES:
Introduction

A file is a collection of related data stored in a disk. The flow of data between program and a
file is called stream. The stream that supplies data to the program is called input stream. The stream
that receives data from the program is called output stream.
Q.No.5 CLASSES FOR FILE STREAM OPERATIONS

C++ contains a set of classes that define the file handling methods.These include
ifstream,ofstream and fstream. These classes are derived from fstreambase ,istream,iostream and
ostream.

The member functions available in the classes are,

ifstream--- It is used for input operations. It contains open(),get(),getline(),read(),seekg() and tellg()


functions.

ostream---It is used for output operations. It contains open(),put(),write(),seekp() and tellp()


functions.

fstream----It supports both input and output operations. It inherits all the member functions from
istream, ostream, fstreambase and iostream.

Fstreambase---It contains open() and close() functions.

Q.No.6 OPENING AND CLOSING A FILE


A file can be opened in two ways. They are,

i) Using constructor

ii) using the member function open()

i) Using constructor
Syntax:
Classname object(“filename”);
Where,

Classsname----ifstream or ofstream

Example:
ofstream f1(“stu.dat”);
It will open the “stu.dat” in output mode. In this mode, we can write data into that file.

Ifstream f2(“stu.dat”)

It will open the “stu.dat” in input mode. In this mode, we can read data from that file.

ii) using the member function open()


Syntax:
Classname objectname;
Objectname.open(“filename”);

ofstream file1;

file1.open(“stu.dat”);

It will open the “stu.dat” in output mode. In this mode, we can write data into that file.

ifstream file2

file2.open(“stu.dat”)

closing a file:
Whenever the operations on a file are over it must be closed.The close() function is
used to close all the opened files.

Syntax:
Objectname.close();
Example:

file1.close();

file2.close();

Q.No.7 DETECTING END-OF-FILE


End of file can be detected using eof() function.It returns true if the end of file (EOF)
is encountered and otherwise it returns false.

Syntax:
Objectname.eof()

Example:
ifstream obj;

Obj.open(“stu.dat”);

while(obj!=0)

--------
}

Q.No.8 FILE POINTERS AND THEIR MANIPULATIONS


There are two types of pointers

i) Input pointer/get pointer

ii) Output pointer/put pointer

Input pointer is used while reading data from the file and output pointer is used while writing data
into the file. Each time an input or output operation takes place, the appropriate pointer is
automatically updated.

Functions for manipulation of file pointers:


The following functions are used for controlling the movement of the file pointer.

i) seekg()

ii) seekp()

iii) tellg()

iv) tellp()

i) seekg()
This function is used to move the input pointer to a specified location.

Syntax:
Object.seekg(offset,refposition);
The refposition takes one of the following three constants.

ios::beg Sets the file pointer at the beginning of the file

ios::cur Sets the file pointer in the current position


ios::end Sets the file pointer at the end of the file
Offset--- number of bytes the file pointer to be moved.

Example:
fstream file;

file.open(“stu.dat”,ios::in);

file.seekg(10,ios::beg) // input file pointer is moved to the 10th byte from the beginning

ii) seekp()
This function is used to move the output pointer to a specified location.

Syntax:
Object.seekp(offset,refposition);
Offset--- number of bytes the file pointer to be moved.
Example:
fstream file;

file.open(“stu.dat”,ios::in);

file.seekp(10,ios::beg) // output file pointer is moved to the 10th byte from the beginning

iii) tellg()
It returns the current position of the input file pointer.

Syntax:
int p=object.tellg();
Example:
fstream file;

file.open(“stu.dat”,ios::in);

file.seekg(10,ios::beg)

int p=file.tellg(); // p value is ‘10’

iv) tellp()
It returns the current position of the output file pointer.

Syntax:
int p=object.tellp();

Example:
fstream file;

file.open(“stu.dat”,ios::in);

file.seekp(10,ios::beg)

int p=file.tellp(); // p value is ‘10’

Q.No.9 SEQUENTIAL INPUT AND OUTPUT OPERATIONS


The file stream classes support a number of member functions for performing the input and
output operations on files.

Functions like put () and get() are designed for handling a single character at a time whereas write()
and read() are designed to write and read blocks of binary data.

Sequential input operations:


The sequential input operations can be performed by using the following functions

i) get()

ii) read()
i) get()

It reads a single character from the file.

Syntax:

Object.get(variablename);
Example:
fstream file;

file.open(“stu.dat”,ios::in);

while(file.eof()!=0)

file.get(ch);

cout<<ch;

ii) read()
This function is used to read a block of data from a file .It handles the data in binary form.

Syntax:

Object.read(char*)&var,sizeof(var));
Sequential output operations:
The sequential output operations can be performed by using the following functions

i) put()

ii) write()

i) get()

This function is used to write a single character into the file.

Syntax:

Object.put(variablename);
Example:

fstream file;

file.open(“stu.dat”,ios::in);

while(file.eof()!=0)

cin>>ch;

file.put(ch);
}

ii) write()

This function is used to write a block of data from a file .

Syntax:

Object.write(char*)&var,sizeof(var));

Example program:

#include<iostream.h>

void main()

fstream file;

file.open(“stu.dat”,ios::in);

while(file.eof()!=0)

cin>>ch;

file.put(ch);

file.close();

fstream file;

file.open(“stu.dat”,ios::in);

while(file.eof()!=0)

file.get(ch);

cout<<ch;

file.close();

getch();

Q.No.10 ERROR HANDLING DURING FILE OPERATIONS


While performing input/output operations on the file, anyone of the following errors may
occur.
 A file being opened doesn’t exist,
 The file name chosen for a new file already exists.
 Try to write in a disk which is full.
 Try to write a file which in read mode.
 Reading beyond the end of file
 Use an invalid file name

The above possible errors can be overcome by using the following member functions.

i) eof() -This function is used to check whether the end of file is reached or not. It returns true, if
end of file is reached; otherwise it returns false

ii) good() --This function is used to check whether there is any errors in a file. It returns a non-
zero (true) value when no error has occurred; otherwise returns zero (false).

iii) bad()---This function is used to check for any unrecoverable errors. If any unrecoverable errors
present, it returns true; otherwise it returns false.

iv) fail()---This function is used to check for any failures in input or output operation. It returns non-
zero (true) when an input or output operation has failed; otherwise it returns false

Q.No.11 COMMAND –LINE ARGUMENTS.


Command Line Arguments are values or parameters passed to a program through the
command line during run time.
Command line arguments are given after the name of the program during the execution of
the program.
In order to pass command line arguments, the main function is passed with two arguments.
void main(int argc, char* argv[])
{

// statements
}

where ,argc refers to the number of arguments passed, and


argv[] is a pointer array which points to each argument passed to the program.

Example program:
#include<iostream.h>
void main(int argc, char *argv[])
{
printf("Number of arguments:\n", argc)
for(int i=0;i<=argc;i++)
{
cout<<argv[i]);
}

getch();
}

Terminal Input:
C:\> example.cpp object oriented programming
Arguments will be assigned as,
4rgc=4
argv[0]=example.cpp
argv[1]= object
argv[2]= oriented
argv[3]= oriented
Output:
Number of arguments:4
example.cpp
object
oriented
programming

You might also like