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

Oop Unit-V

Uploaded by

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

Oop Unit-V

Uploaded by

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

UNIT – V

Contents
• Steams and Files
• Stream classes
• Stream Errors
• File I/O with Streams
• File Pointers
• File I/O with Member functions
• Overloading of extraction and insertion operators
• Memory as stream object
• Command line arguments
• Early V/S Late Binding – in Unit III
C++ I/O
• C++ supports all C set of I/O functions

• Two reasons why we don’t use these functions in C++


• I/O methods of C does not supports OOP
• I/O methods of C does not handle user defined data types such as
class object

• C++ uses concept of stream to implement I/O


Streams in C++

• Stream is sequence of bytes


• Interface between I/O and Program
• Two streams
• Input stream
• Output stream
Extraction
Input stream
From input
stream
Input device

Program
Output stream
Output insert
device Into
output
stream
• Input stream can come from keyboard or any other storage
device.

• Output stream can go to screen or any other storage device.


C++ stream classes
ios

istream ostream

iostream

 ios  base class


 ios is declared as virtual base class so only one copy of members are
inherited by iostream
Stream classes
Class name Contents
ios Basic facilities that are used by all
(general input/output stream class) other input-ouput classes
Istream Inherits properties of ios
(input stream) Has functions like get(), getline(),
read()
Contains operator >>
Ostream Inherits properties of ios
(output stream) Put(), write()
Contains operator <<
Iostream Inherits properties of istream and
(input/ output stream) ostream through multiple inheritance
and thus contains all input and
output functions
Unformatted I/O operations
• Using cin & cout
• Using >> & <<
• void get(char *) istream class
• char get()  istream class(cin)
• Put(ch) ostream class(cout)
• Getline(char, size) 
• Write(ch, size)
example
#include <iostream> #include <iostream>
#include<conio.h> #include<conio.h>

using namespace std; using namespace std;

int main()
int main()
{
{ //cout<<"hello";
//cout<<"hello"; char c;
char c;// get a character from c=cin.get();
cin.get(c); // keyboard
while(c!='\n'){
cout<<c;
while(c!='\n'){
cin.get(c);
cout<<c; // display character }
cin.get(c); //on screen & get another getch();
} return 0;
getch(); }
return 0;
}
#include <iostream> #include <iostream>
#include<conio.h>
#include<conio.h>
using namespace std;
using namespace std;
int main()
int main() {
{ cout<<"enter line"<<"\n";
char c;
cout<<"enter line"<<"\n";
c=cin.get();
char c;
c=cin.get(); while(c!='\n'){
cout.put(c);
while(c!='\n'){ cin.get(c);
cout.put(c);
}
cin.get(c);
cout<<"\n";
cout.put(65);
} getch();
getch(); return 0;
return 0;
}
#include <iostream>
#include<conio.h>

using namespace std;


int main(){

int size = 20;


char name[20];

cout<<"enetr your full name"<<"\n";


cin.getline(name,20);
cout<<"your full name is"<<"\n"<<name<<"\n";

getch();
return 0;
}
#include <iostream>
#include<conio.h>
#include<string.h>

using namespace std;


int main(){

char * string1 = "object";

cout.write(string1,10);

getch();
return 0;
}
Formatted I/O operations
• Formatting output
• It includes : ios class functions, flags, manipulators, user-
defined output functions
• Manipulators in <iomanip.h>

ios class format functions


manipulators Functions Task
Setw() Width() Required field size
Setprecision() Precision() Display no. of digits after decimal point
Setfill() Fill() Specify a character to be filled in unused
portion
Setioflags() Setf() Set format flag, e.g left justified or right
justified
Resetioflags() Unsetf() Clear flag
width

cout.width(5);
cout<<"123";
cout.width(5);
cout<<"45";// by default right justified
precision
 Output truncated to nearest cent
 Tailing zeros are truncated
 Default precision is 6 digits

cout.precision(3);
cout<<sqrt(2)<<"\n";
cout<<3.14159<<"\n";
cout.precision(5);
cout<<4.2992<<"\n";
Fill and setf
cout.fill('*');
cout.width(10);
cout<<"1234"<<"\n";

cout.setf(ios::left, ios::adjustfield);
cout.width(15);
cout<<"viit"<<"\n";
manipulators
Cout<<setw(5)<<setprecision(2)<<1.24567

Cout<<setw(15)<<setioflags(ios::scientific)<<swrt(3)
File

• A file is a collection of related data stored in a particular


area on the disk .The data is stored in disk using the
concept of file .

• The information / data stored under a specific name on a


storage device, is called a file.
ASCII Text files
• A text file can be a stream of characters that a computer can
process sequentially. It is not only processed sequentially
but only in forward direction. For this reason a text file is
usually opened for only one kind of operation (reading,
writing, or appending) at any given time.

• It is a file that stores information in ASCII characters. In text


files, each line of text is terminated with a special character
known as EOL (End of Line) character or delimiter
character. When this EOL character is read or written,
certain internal translations take place.
Binary files
• A binary file is no different to a text file. It is a collection of
bytes. In C++ Programming Language a byte and a character
are equivalent. Hence a binary file is also referred to as a
character stream, but there are two essential differences.
• No special processing of the data occurs and each byte of data is
transferred to or from the disk unprocessed.
• C++ Programming Language places no constructs on the file, and it
may be read from, or written to, in any manner chosen by the
programmer.
• It is a file that contains information in the same format as it
is held in memory. In binary files, no delimiters are used for
a line and no translations occur here.
File Handling in C++
• Why use File Handling
• For permanent storage.
• The transfer of input - data or output - data from one computer to
another can be easily done by using files.

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
File Stream Classes
• Ifstream :- provides input operations. Contains open() with
default input mode. Inherits the functions get(), getline(),
read(), seekg() and tellg() function from istream.

Ofstream :- provides output operations. Contains open() with


default output mode. Inherits put(), seekp(), teelp() and write()
function from ostream.

Fstream :- provides support for simultaneous input and output


operations. Contains open() with default input mode. Inherits all
the function from isteram and ostream classes through iostream
fstream
• <fstream> header file.

• void open (const char* filename, ios_base::openmode mode =


ios_base::in | ios_base::out);

• in – file is opened for input. out – file is opened for output. binary
– binary file is opened. ate – output position is set to the end of
the file when a file is opened. app - all the outputs are appended
to the existing contents of the file. trunc – erase data from file.

• The default value for fstream mode parameter is in | out.


• file is opened for reading and writing when you use fstream class
Functions used in File Handling

Function Operation

open( ) To create a file


close( ) To close an existing file
get( ) Read a single character from a file
put( ) write a single character in file.
read( ) Read data from file
write( ) Write data into file.
Opening a file using open()

The function open() can be used to open multiple files that


use the same stream object.

E.g.
file-stream-class stream-object;
stream-object . open (“filename”);
OPENING FILE USING open()

Stream-object.open(“filename”, mode)

File mode parameter Meaning


ios::app Append to end of file
ios::ate go to end of file on opening
ios::binary file open in binary mode
ios::in open file for reading only
ios::out open file for writing only
ios::nocreate open fails if the file does not exist
ios::noreplace open fails if the file already exist
delete the contents of the file if it
ios::trunc
exist
Open and close a file
eg:-
ofstream outfile; // create stream
outfile.open (“DATA1”); // connect stream to DATA1
……………………………..
……………………………..
outfile.Close(); //disconnect stream from DATA1
outfile.open(“DATA2”); //connect stream to DATA2
……………………………..
……………………………..
outfile . close();
……………………………..
File Pointer

Each file have two associated pointers known as the file


pointers. One of them is called the input pointer (or get
pointer) and the other is called the output pointer (or put
pointer). The input pointer is used for reading the contents
of a given file location and the output pointer is used for
writing to a given file location.
Functions for Manipulating File Pointers
When we want to move file pointer to desired position then
use these function to manage the file pointers.

Seekg () = moves get pointer (input) to a


specified location
Seekp () = moves put pointer (output) to a
specified location
tellg () = gives the current position of the get pointer
tellp () = gives the current position of the put pointer
fout . seekg(0, ios :: beg) -- go to start
fout . seekg(0, ios :: cur) -- stay at current position
fout . seekg(0, ios :: end) -- go to the end of file
fout . seekg(m, ios :: beg) -- move to m+1 byte in the file
fout . seekg(m, ios :: cur) -- go forward by m bytes from
the current position
fout . seekg(-m, ios :: cur) -- go backward by m bytes
from the current position
fout . seekg(-m, ios :: end) -- go backward by m bytes
from the end
Put( ) and get( ) functions

• The function put( ) write a single character to the


associated stream. Similarly, the function get( ) reads a
single character from the associated stream.
read( ) and write( ) functions
file . read ((char *)&V , sizeof (V));
file . Write ((char *)&V , sizeof (V));

These function take two arguments. The first is


the address of the variable V , and the second is
the length of that variable in bytes . The address
of variable must be cast to type char * (i.e pointer
to character type) .
bool is_open( );
• This function returns true if the file is opened and
associated with this stream. Otherwise, it returns false:

fstream file;

//open file text.txt for input and output


file.open("test.txt");
if (!file.is_open())
cout << " Cannot open file!" << endl;
char get( )
Extracting characters from stream

fstream file;

//open file text.txt for input and output


file.open("test.txt");
if (!file.is_open()) cout << " Cannot open file!" << endl;

//write ten numbers to test.txt


for (int i = 0; i != 10; ++i)
file << i << endl; //write i with newline character to text.txt

file.seekg(ios::beg); //reset position of the input

//read first 5 number from test.txt


for (int i = 0; i != 5; ++i)
{ //show read value on screeen
cout << (char)file.get() << endl;
}
More functions
istream& getline (char* str, streamsize n, char delim = ‘\n’);

int peek(); // returns next character

seekg (int pos); // set the position of the curser

int tellg(); // get the current position of the curser


Steps
• File I/O is a five-step process:
1. Include the header file fstream in the program.
2. Declare file stream object.
3. Open the file with the file stream object.
4. Use the file stream object with >>, <<, or other
input/output functions.
5. Close the files.
Program to write in a text file
#include <fstream>
using namespace std;
int main( ) {
ofstream fout;
fout.open("out.txt");
char str[300] = "Time is a great teacher but
unfortunately it kills all its pupils. Berlioz";
//Write string to the file.
fout << str;
fout.close();
return 0; }
Program to read from text file and display it
#include<fstream>
#include<iostream>
using namespace std;
int main( ) {
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof( )) {
fin.get(ch);
cout << ch;
} fin.close( );
return 0;
}
Program to count number of characters
#include<fstream>
#include<iostream>
using namespace std;
int main( ) {
ifstream fin;
fin.open("out.txt");
int count = 0;
char ch;
while(!fin.eof()) {
fin.get(ch);
count++;
}
cout << "Number of characters in file are " << count; fin.close( );
return 0;
}
Program to count number of words
#include<fstream>
#include<iostream>
using namespace std;
int main( ) {
ifstream fin;
fin.open("out.txt");
int count = 0;
char word[30];
while(!fin.eof( )) {
fin >> word;
count++;
}
cout << "Number of words in file are " << count;
fin.close();
return 0;
}
Program to count number of lines
#include<fstream>
#include<iostream>
using namespace std;
int main() {
ifstream fin;
fin.open("out.txt");
int count = 0;
char str[80];
while(!fin.eof( )) {
fin.getline(str,80);
count++;
}
cout << "Number of lines in file are " << count;
fin.close( );
return 0;
}
Program to copy contents of file to another file.
#include<fstream>
using namespace std;
int main() {
ifstream fin;
fin.open("out.txt");
ofstream fout;
fout.open("sample.txt");
char ch;
while(!fin.eof( )) {
fin.get(ch);
fout << ch;
}
fin.close( );
fout.close( );
return 0;
}
Program to understand all operations
#include<iostream>
#include<fstream>

Class student
{
Public:
Struct stu
{
char name[20];
int roll;
}s;
Void put_data();
Void get_data();
};
void student :: put_data()
{
cout<<"enter name ";
cin>>s. name;
cout<<"enter roll ";
cin>>s. roll;
file. Open ("hit. txt“ , ios :: out | ios :: app);
file. write ((char *)this, sizeof (student));
file. close();
get_data();
}
void student :: get_data()
{
int temp;
cout<<"enter roll no. ";
cin >>temp;
fstream file;
file. open ("hit . txt", ios :: in);
file.seekg(0,ios::beg);
While (file . read ((char *) this, sizeof (student)))
{
If (temp==s. roll)
{
cout<<"student name "<< s . name<<"\n";
cout<<"student roll "<< s . roll;
}
}
getch ();
}
void main()
{
clrscr();
student st;
st .put_data();
}
One more example
fstream file;

//open file text.txt for input and output


file.open("test.txt");

//check if file is opened


if(!file.is_open()) cout << " Cannot open file!" << endl; /

//write a message to file file << "This is the first line " << endl
<< "This is the second line" << endl;

file.seekg(ios::beg);//reset position of the input


//read first 5 number from test.txt
for (int i = 0; i != 5; ++i) {
//show read value on screeen
cout << (char)file.get() << endl;
}

//get the next character from file


char next = file.get(); cout << "The next character is " <<
(char)next << endl;
//reset position again
file.seekg(ios::beg);
char* str = new char[50];

//extract first line into str


file.getline(str, 50);

//show first line


cout << str << endl;

//ignore next extracted character

file.ignore();
//show the next character without extracting it from file
cout << "Peek " << (char) file.peek() << endl;

//get current position cout << "Current position is " <<


file.tellg() << endl;

//after all work with file is done


//close it
file.close();
Stream errors
• Streams have error state
• Flags are set if error occurs
Error Flags
Iostate flag Error category

ios_base::goodbit Everything's fine

ios_base::eofbit An input operation reached the end


of an input sequence

ios_base::failbit An input operation failed to read


the expected character, or
An output operation failed to
generate the desired characters

ios_base::badbit Indicates the loss of integrity of the


underlying input or output
sequence
• ios::goodbit : This state flag indicates that there is no error
with streams. In this case the status variables has value 0.

• ios::eofbit: This state flag indicates that the input operation


reached end of input sequence.

• ios::badbit: This state flag indicates that the stream is


corrupted and no read/write operation can be performed.

• ios::iostate ios::rdstate(): This function returns the state of


a stream object of type iosteate.
Stream Errors
• ios class
• bool ios::good() : This function returns true when everything is okay,
that is , when there is no error conditions.
• bool ios::eof(): This function returns true if the input operation
reached end of input sequence.

• bool ios::bad(): This function returns true if the stream is corrupted


and no read/write operation can be performed. For example in an
irrecoverable read error from a file.

• bool ios::fail(): This functions returns true if the input operation


failed to read the expected characters, or that an output operation
failed to generate the desired characters. When in fail condition the
stream may not be corrupted.
Stream functions to check state
ios_base member function Effect

bool good() True if no error flag is set

bool eof() True if eofbit is set

bool fail() True if failbit or badbit is set

bool bad() True if badbit is set

bool operator!() As fail()

operator void*() Null pointer if fail() and non-null


value otherwise

iostate rdstate() Value of stream state


Example
using std::ios;
using std::cout;
using std::endl;
using std::cin;

int main() {
int integerValue;
cout<<"Before a Bad input operation: "
<<"\ncin.rdstate(): “<<cin.rdstate()
<<"\n cin.eof():"<<cin.eof()
<<"\ncin.fail(): “<<cin.fail()
<<"\ncin.bad(): “<<cin.bad()
<<"\ncin.good(): "<<cin.good()
<<"\n\nExpects an integer, but enter a character: ";
cin>>integerValue;
cout<<endl;
cout<<"After a bad input operation: "
<<"\n cin.rdstate(): "<<cin.rdstate()
<<"\n cin.eof(): "<<cin.eof()
<<"\n cin.fail(): "<<cin.fail()
<<"\n cin.bad(): "<<cin.bad()
<<"\n cin.good(): "<<cin.good()
<<endl<<endl;
cin.clear(ios::goodbit);
cout<<"After cin.clear()"
<<"\ncin.fail(): "<<cin.fail()
<<"\ncin.good(): "<<cin.good()
<<endl<<endl;

return 0; }
Error Handling function in files
RETURN VALUE AND
FUNCTION
MEANING
returns true (non zero) if end
of file is encountered while
eof()
reading; otherwise return
false(zero)
return true when an input or
fail()
output operation has failed
returns true if an invalid
operation is attempted or any
bad()
unrecoverable error has
occurred.
returns true if no error has
good()
occurred.
Command line arguments in C++
• If any input value is passed through command prompt at the time
of running of program is known as command line argument.

• In Command line arguments application main() function will takes


two arguments that is;
• argc
• argv

• argc: argc is an integer type variable and it holds total number of


arguments which is passed into main function. It take Number of
arguments in the command line including program name.
• argv[ ]: argv[] is a char* type variable, which holds actual
arguments which is passed to main function.
example
#include<iostream>
#include<conio>
int main(int argc, char* argv[ ]) {
int i;
cout<<"Total number of arguments: "<<argc;
for(i=0;i< argc;i++) {
cout<<endl<< i<<"argument: "<<argv[i];
return 0;
}
}

Run from command prompt with any no. of values passed at run
time.
Overloading stream insertion (<<) and extraction
(>>) operators
• In C++, stream insertion operator “<<” is used for output
and extraction operator “>>” is used for input.

• We must know following things before we start overloading


these operators.
1) cout is an object of ostream class and cin is an object
istream class
2) These operators must be overloaded as a global function.
And if we want to allow them to access private data
members of class, we must make them friend.
example
#include <iostream>
using namespace std;

class Complex{
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {
real = r; imag = i;
}
friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c);
};
ostream & operator << (ostream &out, const Complex &c) {
out << c.real;
out << "+i" << c.imag << endl;
return out;
}

istream & operator >> (istream &in, Complex &c) {


cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imagenory Part ";
in >> c.imag;
return in;
}
int main( ) {
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}
• Output:
• Enter Real Part 10 Enter Imaginary Part 20 The complex
object is 10+i20
Thank you !!

You might also like