Sunteți pe pagina 1din 8

Prepared by V.L.

Kartheek

UNIT-IV
C++ I/O
Syllabus:-

➢ I/O using C functions,


➢ Stream classes’ hierarchy,
➢ Stream I/O,
➢ File streams and String streams,
➢ Overloading operators,
➢ Error handling during file operations,
➢ Formatted I/O.

I/O using C functions:-

C programming input output functions

We can classify I/O function into two categories:

1. Console I/O function


2. File I/O function

1. Console Input-Output functions

Console simply means screen and keyboard. There are two types of a console I/O functions:

• Formatted input-output function


• Unformatted input-output function

The major difference is that formatted function allows us to format the input from the keyboard and the
output to be displayed on the screen.

1
Prepared by V.L.Kartheek

File Input/output in C:-

file represents a sequence of bytes on the disk where a group of related data is stored. File is created for
permanent storage of data. It is a readymade structure.

In C language, we use a structure pointer of file type to declare a file.

FILE *fp;

C provides a number of functions that helps to perform basic file operations. Following are the functions,

Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the begining point
Stream classes’ hierarchy:-
File Stream Classes :-
➔ C++ provides several classes to work with stream based I/O. Such classes are known as stream classes and
they are arranged in a hierarchy shown below:

(Fig) File Stream Classes

2
Prepared by V.L.Kartheek

Stream I/O:-
➔ C/C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs (just
like water and oil flowing through a pipe). In input operations, data bytes flow from an input source
(such as keyboard, file, network or another program) into the program.

3
Prepared by V.L.Kartheek

File streams and String streams:-


Data type Description
ofstream
This is used to create a file and write data on files
ifstream
This is used to read data from files

fstream This is used to both read and write data from/to


files

Defining and Opening a File :-

→ The function open() can be used to open multiple files that use the same stream object.
Syntax:-
file-stream-class stream-object;
stream-object.open("filename");

Example:-
ofstream outfile; // create stream
outfile . open ("data1"); // connect stream to data1

Closing a File :-
→ A file must be close after completion of all operation related to file.
→ For closing file we need close() function.
Syntax :-
outfile.close();
String streams:-

➔ The string stream associates a string object with a string. Using this we can read from string as if it were
a stream like cin.
➔ The Stringstream has different methods. These are like below −

Basic methods are: –

clear(): Used to clear the stream

str(): To get and set the string object whose content is present in stream

operator << : This will add one string into the stringstream

operator >> : This is used to read from stringstream object.

4
Prepared by V.L.Kartheek

Application:

Count number of words in a string

Examples:
Input : Asipu Pawan Kumar
Output : 3

Input : Geeks For Geeks Ide


Output : 4

Overloading operators:-
➔ C++ incorporates the option to use standard operators to perform operations with classes in
addition to with fundamental types.

Example:
int sum, b, c; sum = b + c;

This is valid code in C++, since the different variables of the addition are all fundamental types.

TYPES
1. Unary operator overloading
2. Binary operator overloading

UNARY OPERATOR OVERLOADING


➔ Important feature of Object Oriented Programming.
➔ It is because by using this facility programmer would be able to create new definitions to
existing operators.
➔ Unary Operators: Operates on only one operand. e.g.: ++ -- ! ~ unary minus ects.
➔ The above operators can be overloaded using the keyword operator.
Syntax
class classname
{
public:
return_type operator operator-symbol(argument-list); //Declaration
};
//Definition
returntype classname :: operator operator-symbol(argument-list)
{

<statement block>

5
Prepared by V.L.Kartheek

BINARY OPERATOR OVERLOADING


➔ Important feature of Object Oriented Programming.
➔ It is because by using this facility programmer would be existing operators. able to create new
definitions to existing operators.
➔ Binary operators operate on more than one operand.
➔ The above classification of operators can be overloaded using the keyword operator.

Syntax:-

class classname
{
public:
return_type operator operator-symbol(argument-list); //Declaration
};
//Definition
returntype classname :: operator operator-symbol(argument-list)
{

<statement block>

Error handling during file operations:-

➢ To check for errors during file operations , C++ file streams inherit 'stream-state' members from the
ios class that store the information on the status of a file that is being currently used.
➢ The current state of the I/O system is held in an integer, in which the following flags are encoded:
Name Meaning
eofbit 1 when end-of-file is encountered, 0 otherwise.
failbit 1 when a non-fatal I/O error has occurred, 0 otherwise
badbit 1 when a fatal I/O error has occurred, 0 otherwise
goodbit 0 value

C++ Error Handling Functions

➢ There are several error handling functions supported by class ios that help you read and process the
status recorded in a file stream.

Following table lists these error handling functions and their meaning:

6
Prepared by V.L.Kartheek

Function Meaning
int bad() Returns a non-zero value if an invalid operation is attempted or any unrecoverable error has
occurred. However, if it is zero (false value), it may be possible to recover from any other
error reported and continue operations.
int eof() Returns non-zero (true value) if end-of-file is encountered while reading; otherwise returns
zero (false value).
int fail() Returns non-zero (true) when an input or output operation has failed.
int good() Returns non-zero (true) if no error has occurred. This means, all the above functions are
false. For example, if fin.good() is true, everything is okay with the stream named as fin and
we can proceed to perform I/O operations. When it returns zero, no further operations can
be carried out.
clear() Resets the error state so that further operations can be attempted.

➢ The above functions can be summarized as eof() returns true if eofbit is set;
➢ bad() returns true if badbit is set. The fail() function returns true if failbit is set;
➢ the good() returns true there are no errors. Otherwise, they return false.

FormattedI/O:-
Console input / output function take input from standard input devices and compute and give output to
standard output device.
Generally, keyboard is standard input device and monitor is standard output device.

Formatted console input output functions are -setw(), setfill(), setprecision(), hex,oct,dec

setw():
#include<iostream.h>
#include<iomanip>
int main()
{
int x=10;
cout<<setw(20)<<variable;
return 0;
}
Output:
10
setfill():
#include<iostream.h>
#include<iomanip>
usingnamespacestd;
int main()
{
int x=10;
cout<<setw(20);
cout<<setfill('#')<<x;
return 0;
}
Output:
##################10

7
Prepared by V.L.Kartheek

Setprecision():
#include<iostream.h>
#include<iomanip>
int main()
{
float x=10.12345;
cout<<setprecision(5)<<x;
return 0;
}
Output:
10.123
hex,oct,dec:
#include<iostream.h>
#include<iomanip>
int main()
{
cout<<hex<<10<<endl;
cout<<oct<<10<<endl;
cout<<dec<<10<<endl;
return 0;
}

Output:

S-ar putea să vă placă și