0% found this document useful (0 votes)
23 views70 pages

Unit-IV Oop Part-I RBK

The document explains the concept of streams in C++, which serve as an interface for input and output operations with files and devices. It details the classes used for file handling, such as ifstream, ofstream, and fstream, and outlines the process of opening, reading, writing, and closing files. Additionally, it covers error handling, file pointers, and the use of command-line arguments in C++ programs.

Uploaded by

jay thorat
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)
23 views70 pages

Unit-IV Oop Part-I RBK

The document explains the concept of streams in C++, which serve as an interface for input and output operations with files and devices. It details the classes used for file handling, such as ifstream, ofstream, and fstream, and outlines the process of opening, reading, writing, and closing files. Additionally, it covers error handling, file pointers, and the use of command-line arguments in C++ programs.

Uploaded by

jay thorat
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/ 70

 A stream is an abstraction that represents a

device on which operations of input and


output are performed.

 A stream can be represented as a source or


destination of characters of indefinite
length depending on its usage.
ios

istream ostrea
fstreambase
get() m
getline( put()
) read() iostrea write()
>> m <<

Ifstrea Ofstrea
fstream
m m
Open() Open()
Tellg() Tellp()
Seekg() Seekp()
 We turn our computers on and off
◦ The contents of our main memory is transient
 We like to keep our data
◦ So we keep what we want to preserve on disks and similar
permanent storage
 A file is a sequence of bytes stored in permanent
storage
◦ A file has a name
◦ The data on a file has a format
 We can read/write a file if we know its name and
format
0: 1: 2:

 At the fundamental level, a file is a sequence of


bytes numbered from 0 upwards
disk I/O system Main memory

iostreams
Objects
Files
(of various types)
(sequences of bytes)
Program

Input Outp ut

Stream
Stream

Files
 To perform input and output, a C + + program:
1. Construct a stream object.
2. Connect (Associate) the stream object to an
actual IO device (e.g., keyboard, console, file,
network, another program).
3. Perform input/output operations on the stream,
via the functions defined in the stream's pubic
interface in a device independent manner.
4. Disconnect (Dissociate) the stream to the actual
IO device (e.g., close the file).
5. Free the stream object.
 Streams act as an interface between files and
programs.
They represent as a sequence of bytes and

deals with the flow of data.


Every stream is associated with a class having

member functions and operations for a


particular kind of data flow.

 File Program ( Input stream) - reads


 Program  File (Output stream) – write

All designed into fstream.h and hence needs


to be included in all file handling programs.
 Diagrammatically as shown in next slide
Hierarchy
Diagram

i/p operation on
array bloked
stream
Holds one non
derived data
member
 Convenient way to deal large quantities of data.
 Store data permanently (until file is deleted).
 Avoid typing data into program multiple times.
 Share data between programs.
 We need to know:

 how to "connect" file to program


 how to tell the program to read data
 how to tell the program to write data
 error checking and handling EOF
When working with files in C + + , the
following classes can be used:
ofstream – writing to a file
ifstream – reading for a file
fstream – reading / writing

When ever we include <iostream.h>,


an ostream object, is automatically
defined – this object is cout.
ios is the base class. ofstream inherits from the class
ostream (standard output class).
istream and ostream inherit from ios
ostream overloaded the operator < <
ifstream inherits from istream (and for standard output.…thus an ofstream
ios) object can use methods and operators
ofstream inherits from ostream (and defined in ostream.
ios)
iostream inherits from istream and
ostream (& ios)
fstream inherits from ifstream,
iostream, and ofstream
Program for Files
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open(“demo.dat”);
fout<<“Welcome to c++”;
return 0;
}
Program for Files
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
char ch;
fin.open(“demo.dat”);
fin>>ch;
cout<<ch;
return 0;
}
Output: W
Program for Files
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
char ch;
fin.open(“demo.dat”);
fin>>ch;
While(!fin.eof())
{
cout<<ch;
fin>>ch;
}
return 0;
}
Output: Welcometoc++”
Program for Files
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
char ch;
fin.open(“demo.dat”);
While(!fin.eof())
{
ch=fin.get();
cout<<ch;
}
return 0;
}
Output: Welcome to c++”
Stream Classes required for File i / o :
 ifstream
 ofstream
 fstream
1: To access file handling routines:
#include <fstream.h>
2: To declare variables that can be used to access file:
ifstream in_stream;
ofstream out_stream;
3: To connect your program's variable (its internal name) to
an external file (i.e., on the Unix file system):
in_stream.open("infile.dat");
out_stream.open("outfile.dat");
4: To see if the file opened successfully:
if (in_stream.fail())
{ cout << "Input file open failed\
n"; exit(1); // requires
<stdlib.h>}
5: To get data from a file (one option), must declare
a variable to hold the data and then read it using
the extraction operator:
int num;
in_stream >> num;
[Compare: cin >> num;]
6: To put data into a file, use
insertion operator:
out_stream << num;
[Compare: cout << num;]
NOTE: Streams are sequential – data is read and
written in order – generally can't back up.
7: When done with the
file: in_stream.close();
out_stream.close();
 Every file maintains two pointers called
get_pointer (in input mode file) and put_pointer
(in output mode file) which tells the current
position in the file where reading or writing will
takes place.
 These pointers help attain random access in
file.
That means moving directly to any location in the
file instead of moving through it sequentially.
 By default reading pointer is set at the beginning
and writing pointer is set at the end.(when you
open file in app mode)
 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 manipulation of 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.
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.
With one argument :
seekg(k) where k is absolute position from
the beginning. The start of the file is byte
0 Begi File End
n

k ^
bytes File pointer

The seekg() function with one argument


 With two arguments :
 the first argument represents an offset
from a particular location in the
 file.
the second specifies the location from
which the offset is measured.
 Begin End

^
Offset from
Begin

The seekg() function with two argument


With two arguments :
Begin End

^
Offset from Begin

^
Offset from end

^
Offset from
current
position
infile.seekg(10); =>
 Moves the file pointer to the byte number 10.
 The bytes in a file are numbered beginning from zero.
 Thus, the pointer will be pointing to the 11th byte in the file.

Specifying the offset :


The seek functions seekg() and seekp() can also be used with two
arguments as follows:
seekg(offset, refposition);
seekp(offset,
refposition);
The parameter offset represents the number of bytes the file pointer
to
be moved from the location specified by the parameter refposition.

The refposition takes one of the following these constant defined in the
ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file.
 Sometimes during file operations, errors may also
occur
 For example, a file being opened for reading might
not exist.
 Or a file name used for a new file may already exist.
 Or an attempt could be made to read past the end-of-
file. Or
such as invalid operation may be performed.
 There might not be enough space in the disk for
storing data.
 To check for such errors and to ensure smooth
processing, 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 :
 There are several error handling functions supported by class
ios that help you read and process the status recorded in a
file stream .
open()
An open file is represented within a program by
a stream and any input or output operation
performed on this stream object will be applied to
the physical file associated to it .
In order to open a file with a stream object we use its
member function open:
Syntax:-

open (filename, mode);


Where filename is a string representing the name of
the file to be opened, and mode is an optional
parameter with a combination of the following flags:
10/19/2020 33
Example:-
 ofstream myfile;
myfile.open ("example.txt", ios::out | ios::app
| ios::binary);
Each of the open member functions of classes
ofstream, ifstream and fstream has a default
mode that is used if the file is opened
without a second argument:

class default mode parameter


ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
 When we are finished with our input and output
operations on a file
 we shall close it so that the operating system is
notified and its resources become available again.
 For that, we call the stream's member function
close.
 This member function takes flushes the
associated
buffers and closes the file:
myfile.close();
 Once this member function is called, the
stream object can be re-used to open another
file, and the file is available again to be
opened by other processes.
 Ostream f1;
 F1<<“hello”;
 The write() function is used to write object or
record (sequence of bytes) to the file. A record
may be an array, structure or class.
 Syntax of write() function
fstream fout;
fout.write( (char *) &obj,
sizeof(obj) );

&obj : Initial byte of an


object stored in memory.

sizeof(obj) : size of object represents the total


number of bytes to be written from initial byte.
 The read() function is used to read
object (sequence of bytes) to the file.
Syntax of read() function

fstream fin;
fin.read( (char *) &obj,
sizeof(obj) );
 &obj : Initial byte of an object stored in file.
sizeof(obj) : size of object represents the
total number of bytes to be read from
initial byte.
 The read() function returns NULL if no data
read.

Command-line arguments are given after
the name of the program in command-line
shell of Operating Systems.
 To pass command line arguments, we

typically define main() with two


arguments : first argument is the number
of command line arguments and second is
list of command-line arguments.
Syntax:-
int main(int argc, char *argv[])
{ /* ... */ }
argc (ARGument Count) is int and stores number of command-
line arguments passed by the user including the name of the
program. So if we pass a value to a program, value of argc would
be 2 (one for argument and one for program name). The value of
argc should be non negative.

argv(ARGument Vector) is array of character pointers


listing all the arguments.
If argc is greater than zero,the array elements from argv[0]
to argv[argc-1] will contain pointers to strings.
Argv[0] is the name of the program , After that till
argv[argc-1] every element is command -line arguments.
Example:-
#include <iostream>
using namespace
std;

int main(int argc,


char** argv)
{
cout < < "You have
entered " < < argc
<< "
arguments:"
< < "\n";

for (int i = 0; i < argc; + + i )


cout < < argv[i] < < "\
 Input:
$ g + + mainreturn.cpp - o main
$./main SE Div3 Class

Output:-
You have entered 4 arguments:
./main
SE
Div3
Class
 They are passed to main() function.
 They are parameters/arguments supplied to
the program when it is invoked.
 They are used to control program from
outside instead of hard coding those
values inside the code.
 argv[argc] is a NULL pointer.
 argv[0] holds the name of the program.
 argv[1] points to the first command line
argument and argv[n] points last argument.
 You pass all the command line arguments
separated by a space, but if argument
itself has a space then you can pass such
arguments by putting them inside double
quotes “” or single quotes ”.
Example:-
#include<stdio.h>

int main(int argc,char* argv[])


{
int counter;
cout<<"Program Name Is:“<<argv[0];
if(argc==1)
cout<<"\nNo Extra Command Line Argument Passed Other
Than Program Name";
if(argc>=2)
{
c o ucout<<"\nNumber
t < < " \ n - - - - F o l l o w i nOf Arguments
g Are Passed:“<<argc;
The Command Line Arguments
Pa
ssed----";
for(counter=0;counter<argc;counter++)
cout<<"\nargv[counter]: “<<argv[counter]);
}
return 0;
}
 Without argument: When the above code is
compiled and executed without passing
any argument, it produces following
output.
./a.out
Output:-
Program
Name Is:
./a.out
No Extra Command Line Argument Passed
Other Than Program Name
 Three arguments : When the above code is
compiled and executed with a three
arguments, it produces the following output.
 ./a.out First Second Third
 Program Name Is: ./a.out
 Number Of Arguments Passed: 4 - - - -
Following Are The Command Line Arguments
Passed----
 argv[0]: ./a.out
 argv[1]: First
 argv[2]: Second
 argv[3]: Third
 Single Argument : When the above code is
compiled and executed with a single
argument separated by space but inside
double quotes, it produces the following
output.
 ./a.out "First Second Third"
 Program Name Is: ./a.out
 Number Of Arguments Passed: 2 - - - -
Following Are The Command Line Arguments
Passed----
 argv[0]: ./a.out
 argv[1]: First Second Third
 Single argument in quotes separated by space
: When the above code is compiled and
executed with a single argument separated
by space but inside single quotes, it
produces the following output.
 ./a.out 'First Second Third'
 Program Name Is: ./a.out
 Number Of Arguments Passed: 2 - - - -
Following Are The Command Line Arguments
Passed----
 argv[0]: ./a.out
 argv[1]: First Second Third
 The two keywords cout in C + + and cin in
C + + are used very often for printing
outputs and taking inputs respectively.
 These two are the most basic methods
of taking input and printing output in
C++.
 To use cin and cout in C + + one must include
the header file iostream in the program.
 iostream: iostream stands for standard input-
output stream. This header file contains
definitions to objects like cin, cout, cerr etc.
 iomanip: iomanip stands for input output

manipulators. The methods declared in this files


are used for manipulating streams. This file
contains definitions of setw, setprecision, etc.
 fstream: This header file mainly describes the file

stream. This header file is used to handle the


data being read from a file as input or data being
written into the file as output.
 Usually the standard output device is
the display screen.
 The C + + cout statement is the instance
of the ostream class.
 It is used to produce output on the
standard output device which is usually the
display screen.
 The data needed to be displayed on the
screen is inserted in the standard
output stream (cout) using the
insertion operator(<<).

Usually the input device in a computer is
the keyboard.
 C + + cin statement is the instance of the
class istream and is used to read input
from the standard input device which is
usually a keyboard.
 The extraction operator(>>) is used along
with the object cin for reading inputs.
 The extraction operator extracts the data
from the object cin which is entered using
the keyboard.
 The C + + cerr is the standard error
stream which is used to output the
errors.
 This is also an instance of the iostream
class.
 As cerr in C + + is un-buffered so it is used
when one needs to display the error
message immediately.

It does not have any buffer to store the
error message and display later.
// c++ program to implement the cerr
#include <iostream>
using namespace std;

// Driver code
int main()
{
cerr << "the message displayed is
unbuffered";
return 0;
}

Output:
 This is also an instance of iostream class
and used to display errors .
 but unlike cerr the error is first inserted into a
buffer and is stored in the buffer until it is
not fully filled.
 The error message will be displayed on
the screen too.
// c++ program to implement the cerr
#include <iostream>
using namespace std;

// Driver code
int main()
{
clog << "the message displayed is buffered";
return 0;
}
Output:
 cerr is the standard error stream which is used to
output the errors.
 It is an instance of the ostream class.
 As cerr stream is un-buffered so it is used when
we need to display the error message
immediately and does not store the error
message to display later.
 The object of class ostream that represents the
standard error stream oriented to narrow
characters(of type char). It corresponds to the C
stream stderr.
The “c” in cerr refers to “character” and ‘err ’
means “error”, Hence cerr means “character
error”. It is always a good practice to use cerr to
display errors
 / / C + + program to illustrate std::cerr

 #include <iostream>
 using namespace std;

 / / Driver Code
 int main()
 {

 / / This will print "Welcome to GfG"


 / / in the error window
 cerr < < "Welcome to GfG! :: cerr";

 / / This will print "Welcome to GfG"


 / / in the output window
 cout < < "Welcome to GfG! :: cout";
 return 0;
 }
We can treat a part of memory as a Stream Object
and insert data into it in the same way as it is in
a file. This is called In-Memory Formatting.

Example:- Functions in GUI environment that


write data in a Dialog Box or a Window that
needs string type data, even if it is a string
numbers.

This method allows composing this string with


different types of formatting using iostreams in a
part of the memory and then calling a GUI
Function and sending this string in the dialog
box as an argument
 A group of Stream Classes implement this
type of In - Memory Formatting.
 Output in memory is ostrstream class
derived from ostream class.
 Memory has istrstream class for
Input derived from istream
class.
 To use Memory Stream Objects, we have to
include the strstream.h Header File in our
program.
#include<strstream>
#include<iostream>
#include<fstream>
using namespace std;
const int size=80;
int main()
{
char mbuf[size];
ostrstream o1(mbuf, size);
int oj=77;
double od=890.12;
char ostr1[]="Ram";
char ostr2[]="Sita";
o1<<"oj="<<oj<<endl
<<"od="<<od<<endl
<<"ostr1="<<ostr1<<endl
<<"ostr2="<<ostr2<<endl
<<ends;
cout<<mbuf;
char dummy[20];
int ij;
double id;
char istr1[20];
char istr2[20];
istrstream i1(mbuf, size);
i1>>dummy>>ij>>dummy>>id
>>dummy>>istr1>>dummy>>istr2;
cout<<"\n istr1="<<istr1<<"\n istr2="<<istr2;
return 0;
}
Output:

oj=77
od=890.12
ostr1=Ram
ostr2=Sita

istr1=
istr2=Q8V
Overloading the Extraction and
Insertion Operators
 The operator >> is a Bitwise Right
operator. The operator is overloaded in C+
+ for ‘cin’ to input data to standard input
device.
 The operator is then called as Extraction
Operator because it extract data from input
device (or standard input stream).
 The operator << is a Bitwise Left operator.
The operator is overloaded in C++ for ‘cout’
to output data to standard output device.
 The operator is then called as Insertion
Operator because it Insert data into output
Overloading the Extraction and
Insertion Operators
 These operators are overloaded by most of
the file/stream classes to read data from
streams or write data into streams.
 Insertion Operator << is used to Write
(send) data in program to stream.
 Extraction Operator >> is used to Read
(receive) data from stream to program.
 Syntax:
 ostream&operator<<(ostream&stream,
Typeobj)
{//body of inserter
returnstream;
}
Overloading the Extraction and
Insertion Operators
 We can overload the operator for our
class object to output data from object.

 The operator function is commonly


defined as non member function.

 It is defined as a friend function for the


class, since it has to access members
of the class.

 Example: Complex number program


assignment is the example of it.
Thank You
Memory as a Stream Object Program:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy