0% found this document useful (0 votes)
48 views66 pages

Console I/O Operations Console I/O Operations

Console I/O operations involve functions like get() and put() to read and write characters to the console. File handling uses stream classes like ifstream and ofstream along with functions like open(), close() to access files. Formatted I/O allows controlling formatting of output using stream manipulators, flags and functions like width(), precision() and fill().

Uploaded by

Karan Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
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)
48 views66 pages

Console I/O Operations Console I/O Operations

Console I/O operations involve functions like get() and put() to read and write characters to the console. File handling uses stream classes like ifstream and ofstream along with functions like open(), close() to access files. Formatted I/O allows controlling formatting of output using stream manipulators, flags and functions like width(), precision() and fill().

Uploaded by

Karan Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
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/ 66

Console I/O operations

Put() and get() function


char c; char c;
cin.get (c); cin.get(c);
while(c!= ‘\n’) while(c!= ‘\n’)
{ {
cout<<c; cout.put(c);
cin.get(c); //get 2nd char }
}
Char i/o with get() and put()
main()
{
int count=0;
char c;
cout<<“input text \n”;
cin.get(c);
while( c!= ‘\n’)
{
cout.put(c);
count++;
cin.get(c);
}
cout<<“number of chars”<<count;
}
get(str,max,delim);
const int max=80;
char str[max];
cin.get(str,max,’*’);
cout<<str;
getch();
//delim referes to user specified termination char
which if encountered should terminate the
reading of chars.
//str array of chars
Getline()function
main() cout<<“enter city name
again”;
{ int size=20;
cin.getline(city,size);
char city[20];
cout<<“city”<<city;
cout<<“enter city name”;
cin>>name;
cout<<“enter another
cout<<“city name”<<city;
city”;
cin.getline(city,size);
cout<<“new city”<<city;
}
read(str,max)
const int max=11;
char str[max];
cin.read(str,max);
int count=cin.gcount();
str[count]=‘\0’;
cout<<str;
getch();
//null character is not appended at the end of the
string.so we use gcount() to count number of chars
input by the user.
And later use to append null characte ‘\0’ at the end
of the string.
gcount()
• Member function takes no parameter and
returns the number of chars read during the
preceding input operation.
• Eg:
char str[20];
cin.get(str,20);
int count=cin.gcount();
cout<<“no of chars extracted”<<count ;
ignore(max,delim)
char ch;
cin.get(ch);
While(ch!=‘X’)
{
cin.get(ch);
if(ch>=‘0’ && ch<=‘9’)
cin.ignore();
else
cin.put(ch);
}
return 0;
}
Any numeric digit entered by the user will be ignored from the
stream cin.ignore();
peek(): returns the next char from the
input stream without removing the char
from the stream.
char ch;
cout<<“press f6 or ^Z to exit”;
while(cin.get(ch))
{ Output
if(ch==cin.peek()) aa bb cc
a b c
cin.ignore();
cout.put(ch);
}
return 0;
// will remove duplicate consecutive chars and print it only
once.
Write()
• Output the max number of chars
• Process of displaying write function does not
stop even when the null (‘\0’) is encountered.
• If MAX is greater than the length of the str then
it may display unwanted chars beyond the max
length of the string.
E.g. cout.write(“Anurag”,3);
On execution it will display “Anu” which are first
three chars of the string
Write() function: output the max
number of chars
main()
{
char *string=“bombay”;
int m=strlen(string);
for(int i=0;i<m;i++)
{
cout.write (string,i);
cout<<“\n”;
}
getch();
}
Formatted I/O
• Programmer usually need to display the data
in a particular format depending upon their
requirements.for this c++ provides
– ios stream class flags and member functions
– Manipulators
– User-defined manipulators
ios stream class functions and flag
• Consist of number of member functions which
helps in formatting the output in a variety of
ways:
• width() , precision() , fill() , setf() and unsetf()
width()
cout.width(5); 1 2 4
cout<<124;

cout.width(5);
1 2 4 3 6
cout<<124<<36;

cout.width(5);
1 2 4 3 6
cout<<124;
cout.width(3);
cout<<36;
fill() and precision()

cout.fill(‘#’); # # 1 2 4

cout.width(5);
cout<<124;

cout.precision(3);
cout<<6.7291; 6.729
setf(flags) and unsetf(flags)
• C++ defines some format flags for standard
input and output, which can be manipulated
with the flags(), setf(), and unsetf() functions.
For example,
• cout.setf(ios::left);
User-Defined Manipulators
ostream &manipulator_name(ostream &stream)
{
…………………………………..
// manipulator code
…………………………….
return stream;
}
stream object is a reference to the invoking
object.
ostream &tab(ostream &stream)
{
stream<<‘\t’; or cout<<‘\t’;
return stream;
}
User-defined manipulator tab is invoked
and cout stream object is passed by
reference.
File Handling
<iostream.h>

Istream ostream

Ifstream ofstream

<fstream.h>
• Ifstream: it contains open() function with
default input mode and inherits
get(),getline(),>>,read(),seekg(),tellg() member
functions from istream classes.
• Ofstream: contains open() function with
default output mode and inherits
<<,put(),seekp(),tellp() and write() member
functions from ostream classes.
• fstream: contains open() function with default
i/o and inherit the meber fns from ostream
and istream classes through iostream class.
Opening and closing a file
• ifstream inp_file; // an input file
stream //object for handling input files.

• Ofstream out_file; // an output file


//stream object for handling output files.

• fstream inp_out_file ; // an i/o file


stream //object for handling both input and
output //operations on a file
To input info.into a file using open()
and close() functions
main()
{
ofstream obj;
obj.open(“abc.DAT”);
obj<<“hello”;
obj.close();
getch();
}
To access info.from file
main()
{
char msg[10];
ifstream obj;
obj.open(“abc.DAT”);
obj>>msg;
cout<<msg;
obj.close();
getch();
}
Check before read or write operation
If(! inp_file)
{
cerr<<“file is not opened successfully”;
exit(-1);
}
close()
• After read/write operations on a file,it must
be closed either explicitly calling the close()
member function or closing it implicitly by the
destructor of the appropriate stream class.
• When a file is closed,the disk file is
disconnected from your program and the final
contents of the file are saved on disk.
• inp_file.close();
Opening Files Using Constructor
Instead of first creating file stream object and
then opening the file in a separate statement
using open() function,you can use single
statement for opening a file.
ifstream inp_file(“inp.txt”); // input only
Creates an object inp_file of ifstream class that
connect the filename
To write info.to a file
main()
{
clrscr();
ofstream hello(“abc.TXT”);
hello<<“welcome”;
getch();
}
To read contents of a file
main()
{
char name[30];
ifstream obj(“abc.TXT”);
obj>>name;
cout<<name;
getch();
}
Better
File can be opened using constructor or using open()
member function explicitly.
The method of opening a file using open() is
generally used when different files are to be
connected with the same file stream object at
different times in the program wdout creating
object.
ofstream out1;
out1.open(“ABC1.txt”);
out1.close();
out1.open(“ABC1.txt”);
out1,.close();
• Program to create a file ‘stud.txt’ and store
student information into it using << operator
File Modes
• In the previous section,we opened a file either using
a constructor or by explicitly using the open()
function in the default mode.
• In both cases we specified the filename as the only
argument for opening a file.But actually in addition
to the filename,there is another arg used,which
specifies the opening mode of the file
streamclass file_stream_object;
file_stream_object.open(“filename”,mode);
stream_class file_stream_object(“filename”,mode);
File Mode Parameters
PARAMETERMEANING
• Ios::app Append to end-of file
• Ios::ate goto end of file on opening
• Ios::binary binary file
• Ios::in Open existing file for reading
• Ios::nocreate open fails if file doesn’t exist
• Ios::noreplace open fails if file already exists
• Ios::out creates new file for writing on
• Ios::trunc Deletes contents if it exists
The mode can combine two or more modes using bit wise
or ( | )
File modes
• ios :: in :- it specifies that file is capable of
input and open files for reading.this mode is
used with ifstream class.

• ios :: out :- it specifies that file is capable of


output and open files for writing.this mode
opens file in ios::trunc mode that previous file
contents are discarded.
• ios :: app :- this causes all output to that file
to be appended to the end.

• ios::trunc :- it causes the contents of


preexisting file by the same name to be
destroyed and truncates the file to 0 length.
• ios::nocreate :- it causes the open(), function
to fail if the file does not already exist,it will
not create a new file with that name.
• ios::noreplace :- it causes the open(), function
to fail if the file already exists,it is used when
you want to create a new file and at the same
time.
• ios::binary :- it causes a file to be opened in
binary mode.By default files are opened in
text file.
Example
• Let us consider an example where we want to
open a file for output,but ensure that the data to
be added must be appended to the end of any
existing data in the file.
• ofstream out1(“ABC.txt”,ios::app);
We can also combine two or more opening modes
using bitwise OR(|).
ifstream in1(“xyz.bin”,ios::in|ios::binary);
Following Points to kept in mind while
working with file modes
• The mode ios::app can only be used with output
files as data is only appended at the end of the
file.
• When a file is opened for writing using ios::app
and ios::ate modes then in both the cases we
move to te end of the file.ios::app allows us to
add only at the end of the file.while using ios::ate
mode allows us to add or modify the existing data
anywhere within the file
File Pointers
• To perform i/o operations with a file,there are two
pointers associated with it,
get() put()
Read-Only Mode: When a file is opened in read-only
mode ,the get pointer is automatically set to point to the
beginning of the file so that file can be read from start.
Write-Only Mode: When a file is opened in write mode,the
existing contents of files are erased and put pointer is set
to point at the beginning of the file so that data can be
written from the start.
Append Mode: When a file is opened is append mode,put
pointer is set to point to the end of the file.
Data can be stored in files which can be of two types:

• Text Files: Data is stored in the form of ascii


chars and is normally used for storing stream
of chars with some special chars to mark each
end of line
• Binary File: A BF is the one in which data is
stored in the same way as it is stored in the
main memory for processing.It is stored in
binary format instead of ASCII chars.
Functions associated with file
pointers :
• The seekg() and tellg() functions allow you
to set and examine the get pointer.

• The seekp() and tellp() functions allow you


to set and examine the put pointer.
seekg() and seekp()(moves the file * to a particular
location)
I a m t h e

seekg(pos) moves the get pointer


seekp(pos) moves the put pointer
Both these functions moves the associated file * to some
fixed location specified by pos from the beginning of file.

ifstream_obj.seekg(5);

Moves the get * 5 positions forward in the file from the


begininng. File pointer will now be pointing to char ‘t’
which is at the 6th position.
Another form of seekg() and seekp()
• seekg(offset,start_pos);
• seekp(offset,start_pos);
• offset: number of positions to move either from
its current position,from the beg of the file or
backward or end of the file as sepcified by 2nd
arg start_pos.
• ios::beg - beginning of the file
• ios::cur - current position of the file
• ios::end - end of the file
ifstream_obj.seekg(4,ios::cur);
tellg() and tellp()
• Used to return the current position of the
associated file pointer.
• tellg() provides the current position of get
pointer.
• tellp() provides the current position of put
pointer in the file.
Implementation of ios::out mode
main() cout<<“rollno”;
{ cin>>rollno;
Char name[20];
int rollno,i; obj<<name;
ofstream obj; obj<<rollno;
obj.open(“aaaaa.dat” ,ios::out); }
for(i=0;i<2;i++) obj.close();
{ getch();
cout<<“enter name”; }
cin>>name;
Implementation of ios::app mode
main() cout<<“rollno”;
{ cin>>rollno;
Char name[20];
int rollno,i; obj<<name;
ofstream obj; obj<<rollno;
obj.open(“aaaaa.dat” ,ios::app); }
Cout<<“appending the file”; obj.close();
cout<<“enter name”; getch();
cin>>name; }
Implementation of ios::in mode
main() obj1<<rollno;
{ cout<<name<<rollno;
Char name[20]; } while(obj1);
int rollno,i;
ofstream obj1; obj1.close();
obj1.open(“aaaaa.dat” ,ios::in); getch();
clrscr(); }
do
{
obj1<<name;
Use of get() and put() function
#include<fstream.h> obj1.close();
main() char c;
{ clrscr();
char name[]= “welcome”; ifstream obj2(“aaaa.txt”);
int i; while(obj2)
{
ofstream obj1(“aaaa.txt”);
obj2.get(c);
for (i=0;i<strlen(name);i++)
cout<<c;
{
}
obj1.put(name[i]); obj2.close();
} getch();
}
Use of write() and read() function
#include<fstream.h>
const char *file=“aaaa”;
main()
{
float height [4]={20.2,13.7,78.9,56.9};
ofstream outfile;
outfile.open(file);
outfile.write(char *) &height ,sizeof(height));
outfile.close(); //close file for reading
cntd…………..
for(int i=0;i<4;i++) //clear array from memory
height[i]=0;
ifstream infile;
infile.open(file);
infile.read(char *) &height ,sizeof(height));
for(i=0i<4;i++)
{
cout.height[i];
}
infile.close();
}
File pointers and their manipulations
Default actions:-
Open for reading only H E L L O

input pointer

Open in append mode


H E L L O

output pointer

Open for writing only

o/p pointer
• seekg():- moves get pointer to a specified
location.
• seekp():- moves put pointer to a specified
location.

• tellg():- gives the current position of get


pointer.
• tellp():- gives the current position of the put
pointer.
Error Handling During File Operation
• Attempting to open a file for reading that does
not exists.
• Performing a operation on a file when it Is not
opened for that purpose.eg. Reading a file
when it is opened in a write mode.
• Attempting to open a file with an invalid
filename.
• Trying to read beyond the boundary of the
file(EOF)
• Disk Error while reading/writing to a file.
Error handling function
• Stream state member functions/error
handling are used for checking the open
failure if any,when one attempts to open a file
from the diskette.these are:-
1.eof()
2.fail()
3.bad()
4.good()
eof:-it is used to check whether a file pointer has reached
the end of a file character or not.it returns TRUE if the file
stream object has encountered end of file,otherwise
returns false.

main()
{
ifstream obj;
obj.open(“file_name”);
while(!obj.eof)
{-------
--------------}
}
• Fail():- to check that a file has been opened for i/p or
o/p successfully,or there is an error.if it fails,it returns a
nonzero character.it returns TRUE if the operation has been
unsuccessful such as processing a file which is not opened.

main() fail() function also checks format


errors while reading.
{
Eg: instead of inputting integer, a
ifstream obj;
string is encountered in the input
obj.open(“f_name”);
stream
while(!obj.fail())
{
cout<<“couldn’t open the file”;
continue;
--------------------------
}
}
• Bad():-to check whether any invalid file operation
has been attempted or there is an error.it returns a
nonzero if it is true,otherwise returns zero.
This function reports fatal errors which
main() are non-recoverable and results in the
{ loss of data.
ifstream obj;
obj.open(“f_name”);
if(obj.bad())
{
cout<<“open failure”;
exit(1);
} -----------
}
• Good():- to check whether the previous file operation has
been successful or not.it returns true if there is no error in
the file and all bad(),fail() and eof() function would return
false.

main()
{
ifstream obj;
obj.open(“f_name”);
while(!obj.good())
{--------------
---------------
}
}
Synchronous Exceptions Handling
• Errors that occur at run time are known as
exceptions.
• Eg:
1)division by zero
2) accessing an element that is out of bound f an
array.
3)Unable to open a file
4)Running out of memory and many more.
Exception Handling
• There is another type of exception known as
asynchronous exception that deals error
associated with events like
• Disk I/O completion
• Mouse click
• Network msg arrivals.
For handling such exceptional situations,an error
handling mechanism knwn as exception
handling is provided.
In c++ ,exception handling is
designed to handle only
synchronized exceptions.
Exception Handling Mechanisms
• Whenever an exception occurs in a c++
program portions of a program that detects
the exception can inform that exception has
occurred by throwing it.
Exception Handler
On throwing an exception

The program control immediately stops the step-by-step execution of the code and

Jumps to the separate block of code known as exception handler

Exception handler catches the exception


and process it without troubling the user.
For implementing exception handling:
• C++ provides three constructs:
try , throw and catch.
try
{
// testing condition
throw excp; excp represents type of value to be thrown
}
catch(datatype arg) If the type of value(excp) thrown matches the
datatype of arg,catch block is executed
{
// code for handling exception
}
int main()
{
int x,y;
cout<<“enter num and den:\n”;
cin>>x>>y;
try
{
if(y==0)
throw 10;
cout<<“x/y=“<<x/y;
}
catch(int i)
{
cout<<“exception: division by zero nt allowed”;
}
return 0;

You might also like