Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
SESSION-2019-20
STUDY MATERIAL
FRAGMENT 1
SUBJECT: COMPUTER SCIENCE
CHAPTERS INCLUDED:
Chapter 2: Object Orientated Programming
Chapter 3: Function Overloading
Chapter 4: Class and Objects
Chapter 5: Constructors and Destructors
Chapter 6: Inheritance-Extending Classes
Chapter 7: Data File Handling
TEACHERS’ CONTRIBUTORS:
MOHIT TANDON,PGT COMPUTER SCIENCE, SECTOR-D
NEERU NIGAM,PGT COMPUTER SCIENCE, SECTOR-I
GAJENDRA SINGH DHAMI, PGT COMPUTER SCIENCE, SOUTH-CITY
Study Material - CS-XII Chap - 3 : Object Oriented Programming 1
CHAPTER – 3: OBJECT ORIENTED PROGRAMMING CONCEPTS
Object Oriented Programming follows bottom up approach in program design and emphasizes on safety and security of data..
FEATURES OF OBJECT ORIENTED PROGRAMMING:
Inheritance: Inheritance is the process of forming a new class from an existing class or base class. The base
class is also known as parent class or super class. Derived class is also known as a child class or sub class. Inheritance helps in
reusability of code , thus reducing the overall size of the program
Data Abstraction: It refers to the act of representing essential features without including the background details
.Example : For driving , only accelerator, clutch and brake controls need to be learnt rather than working of engine and other details.
Data Encapsulation: It means wrapping up data and associated functions into one single unit called class.. A class groups its members into three sections :public, private and protected, where private
and protected members remain hidden from outside world and thereby helps in implementing data hiding.
Modularity :
The act of partitioning a complex program into simpler fragments called modules is called as modularity.
It reduces the complexity to some degree and
It creates a number of well defined boundaries within the program .
Polymorphism: Poly means many and morphs mean form, so polymorphism means one name multiple forms. It is the ability for a message or data to be processed in more than one form. C++ implements Polymorhism through Function Overloading , Operator overloading and
Virtual functions .
BY: MOHIT TANDON PGT(CS) LPS SEC-D
Study Material - CS-XII Chap - 3 : Object Oriented Programming 2
Study Material - CS-XII Chap - 3 : Object Oriented Programming 2
.
SHAPE
area()
RECTANGLE() TRIANGLE() CIRCLE()
area(rectangle) Area(triangle) Area(circle)
SOLVED QUESTIONS
Q1. Discuss major OOP concepts briefly.
Ans. Following are the general OOP concepts: 1. Data Abstraction: Data abstraction means, providing only essential information to the outside word and hiding their background details i.e. to represent the needed information in program without presenting the details. 2. Data Encapsulation: The wrapping up of data and operations/functions (that operate on the data) into a single unit (called class) is known as Encapsulation. 3. Modularity: Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules. 4. Inheritance: Inheritance is the capability of one class of things to inherit capabilities or properties from another class. 5. Polymorphism: Polymorphism is the ability for a message or data to be processed in more than one form. Q2. What are programming paradigms? Give names of some popular programming paradigms.
Ans. Programming Paradigm: A Programming Paradigm defines the methodology of designing and implementing programs using the key features and building blocks of a programming language. Following are the different programming paradigms: (i) Procedural Programming (ii) Object Based Programming (iii) Object Oriented Programming Q3. What are the shortcomings of procedural and modular programming approaches?
Ans. Following are the various shortcomings of procedural and modular programming approaches: Procedural Programming is susceptible to design changes. Procedural Programming leads to increased time and cost overheads during design changes. Procedural and Modular programming both are unable to represent real world relationship that exists among objects.
Study Material - CS-XII Chap - 3 : Object Oriented Programming 3
Study Material - CS-XII Chap - 3 : Object Oriented Programming 3
In modular programming, the arrangement of the data can’t be changed without modifying all the functions that access it. Q4. Write a short note on OO programming.
Ans. OOP stands for Object Oriented Programming. In, Object-Oriented Programming (OOP), the program is organized around the data being operated upon rather than the operations performed. The basic idea behind OOP is to combine both, data and its functions that operate on the data into a single unit called object. Following are the basic OOP concepts:
1. Data Abstraction 2. Data Encapsulation 3. Modularity 4. Inheritance 5. Polymorphism
Q5. What is the significance of private, protected and public specifiers in a class?
Ans. A class groups its members into three sections: private, protected, and public. The private and protected members remain hidden from outside world. Thus through private and protected members, a class enforces data-hiding. The public members are accessible everywhere in a program.
ASSIGNMENT
Problem 1: What do you understand by Polymorphism? Give an example in C++ to show its implementation in C++.
Problem 2: What do you understand by Data Encapsulation and Data Hiding?
Problem 3: What is Inheritance? Give an example in C++ to show its implementation in C++.
Problem 4: Illustrate the concept of Inheritance with the help of an example.
Problem 5: Encapsulation is one of the major properties of OOP. How is it implemented in C++? Problem 6: Reusability of classes is one of the major properties of OOP. How is it implemented in
C++? Problem 7: Define the term Data Hiding in the context of Object Oriented Programming. Give a
suitable example using a C++ code to illustrate the same.
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 1 of 6
Notes by:
Neeru Nigam,PGT(CS)
LPS, Sector-I
Chapter 3:Function overloading
It is also known as “Polymorphism”, one of the strongest features
of the Object Oriented Programming Structure. The meaning of Function
overloading is :- the same function can be used differently at different places,
within the same program. That means, we chose one name of the function, but
the function carries different prototypes and definitions , within the same
program.
In general, when we declare an user-defined function, we have to follow
the prototype within the program, number of times we call the function. If we
don’t follow the prototype, we get an error message (Prototype mismatch,
during compliation ) . But because of function overloading feature, we can have
different definitions and different prototypes of the same function in same
program.
We try to understand the above explanation, with the help of an example:
EXAMPLE OF FUNCTION OVERLOADING :
int AREA( int s ) // function 1//
{
return s*s;
}
int AREA ( int l, int b ) // function 2 //
{
return l*b;
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 2 of 6
}
float AREA(int a, int b, int c ) // function 3 //
{
float s, ar;
s=(a+b+c)/2;
ar=sqrt((s*(s-a)*(s-b)*(s-c));
return ar;
}
In the above example , we can see there are three definitions given for the user-
defined function AREA. The first definition has only one parameter, and is
returning the area of a square. The second definition of the function AREA,
carrying two parameters and is returning the area of a rectangle, while the third
definition of the function AREA, is having three parameters and is returning the
area of a triangle.
ADVANTAGE :
As we can understand from the above example, that to get the area of
square, rectangle and triangle, we donot need to declare three different functions
with different names, and more importantly , we are not supposed to write three
programs. We can get the area of our desired shape, according to our need, that
too, within the same program
SOME QUESTIONS :
Q.1 Which function is called during each function call in the program
given below:
int sum (int x); // function 1 //
char choice ( char a , char b ); // function 2 //
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 3 of 6
char choice ( char a ); // function 3 //
float sum( int x, float y); // function 4 //
void main ( )
{
int n;
char ch,ch1;
float n1;
sum(n); // call 1 //
choice(ch); // call 2 //
choice( ch,ch1); // call 3 //
sum (n,n1); // call 4 //
}
Answer :
Call 1 invoke function 1
Call 2 invoke function 3
Call 3 invoke function 2
Call 4 invoke function 4
Q.2 Write the prototype of the overloaded function called sum( ) that add rwo
integers and return an integer, that add two double precision quantity and return
double precision quantity, that add one float and one integer and return float
quantity.
Ans. int SUM ( int , int );
double SUM ( double, double );
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 4 of 6
float SUM ( float, int );
Q.3 What will be the output of the following program :
#include < iostream.h>
int area ( int s )
{
return ( s * s );
}
float area ( int b , int h )
{
return (.5 * b* h );
}
void main ( )
{
cout << area (5)<< endl;
cout<<area(4,3)<< endl;
cout<<area(6,area(3))<<endl;
}
Ans : The output will be:
25
6
27
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 5 of 6
Q.4 Write the output of the following program : ( ASSIGNMENT )
class x
{
void print ( double )
{
cout<<”double”<<endl;
}
void print ( int )
{
cout<<”int”<<endl;
}
void print ( void * )
{
cout<< “void * “<<endl;
}
};
void main ()
{
X obj;
char ch=’A’;
int num=66;
float pi=3.14;
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 6 of 6
char st[]=”ASTRING”;
obj.print(ch);
obj.print(pi);
obj.print(st);
obj.print(num);
}
Q.6 Write declaration of a function COMPOUND_INTREST, having
parameters ( for four different declarations ), illustrating the objective of
function overloading :
1. long p , int T
2. long P , Int T, float r
3. long P, float r
4. int t
NOTE :
When we give more than one declarations of constructor of a class, it is
known as “ Constructor overloading “
Study Material - CS-XII Chap - 4 : Classes and Objects 1
CHAPTER – 4: CLASSES AND OBJECTS
The major components of Object Oriented Programming are . Classes & Objects
A Class is a group of similar objects . Objects share two characteristics: They all have state and
behavior. For example : Dogs have state (name, color, breed, hungry) and behavior (barking,
fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current
speed) and behavior (changing gear, applying brakes). Identifying the state and behavior for real-
world objects is a great way to begin thinking in terms of object-oriented programming. These
real-world observations all translate into the world of object-oriented programming.
Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages)
and exposes its behavior through functions
Classes in Programming :
It is a collection of variables, often of different types and its associated functions.
Class just binds data and its associated functions under one unit there by enforcing
encapsulation.
Classes define types of data structures and the functions that operate on those
data structures.
A class defines a blueprint for a data type.
Class Declaration/Definition :
A class definition starts with the keyword class followed by the class name; and the class body,
enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a
list of declarations.
class <class_name> {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members that can either be data or function declarations, and optionally access specifiers.
[Note: the default access specifier is private.]
Example : class Box
{ int a;
public:
double length; // Length of a box
double breadth; // Breadth of a box
BY: MOHIT TANDON PGT(CS) LPS SEC-D
Study Material - CS-XII Chap - 4 : Classes and Objects 2
Study Material - CS-XII Chap - 4 : Classes and Objects 2
double height; // Height of a box
};
Access specifiers in Classes:
Access specifiers are used to identify access rights for the data and member functions of the class. There are three main types of access specifiers in C++ programming language:
private
public
protected
Member-Access Control
Type of Access
Private
Protected
Meaning
Class members declared as private can be used only by
member functions and friends (classes or functions) of the class.
Class members declared as protected can be used by member
functions and friends (classes or functions) of the class. Additionally,
they can be used by classes derived from the class.
Public Class members declared as public can be used by any function.
Importance of Access Specifiers
Access control helps prevent you from using objects in ways they were not intended to be used. Thus it helps in implementing data hiding and data abstraction.
OBJECTS in C++:
Objects represent instances of a class. Objects are basic run time entities in an object oriented system.
Creating object / defining the object of a class:
The general syntax of defining the object of a class is:-
<Class_name> < object_name>;
In C++, a class variable is known as an object. The declaration of an object is similar to that of a variable of any data type. The members of a class are accessed or referenced
using object of a class.
Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Both of the objects Box1 and Box2 will have their own copy of data members.
Study Material - CS-XII Chap - 4 : Classes and Objects 3
Study Material - CS-XII Chap - 4 : Classes and Objects 3
Accessing / calling members of a classAll member of a class are private by default. Private member can be accessed only by the function of the class itself.Public member of a class can be accessed through any object of the class. They are accessed or called using object of that class with the help of dot operator (.). The general syntax for accessing data member of a class is:-
Object_name.Data_member=value;
The general syntax for accessing member function of a class is:-
Object_name. Function_name (actual arguments);
The dot ('. ') used above is called the dot operator or class member access operator. The dot
operator is used to connect the object and the member function. The private data of a class can
be accessed only through the member function of that class.
Class methods definitions (Defining the member functions)
Member functions can be defined in two places:-
(I) Outside the class definition
The member functions of a class can be defined outside the class definitions. It is only
declared inside the class but defined outside the class. The general form of member function definition outside the class definition is:
Return_type Class_name:: function_name (argument list) { Function body
}
Where symbol :: is a scope resolution operator.
The scope resolution operator (::) specifies the class to which the member being declared
belongs, granting exactly the same scope properties as if this function definition was directly
included within the class definition
class sum
{
int A, B, Total;
public:
void getdata ();
void display ();
};
void sum:: getdata () // Function definition outside class definition Use of :: operator
{ cout<<” \n enter the value of A and B”; cin>>A>>B;
}
Study Material - CS-XII Chap - 4 : Classes and Objects 4
Study Material - CS-XII Chap - 4 : Classes and Objects 4
void sum:: display () // Function definition outside class definition Use of :: operator
{ Total =A+B;
cout<<”\n the sum of A and B=”<<Total; }
(II) Inside the class definition
The member function of a class can be declared and defined inside the class definition.
class sum
{
int A, B, Total;
public:
void getdata () { cout< ”\n enter the value of A and B”; cin>>A>>B;
}
void display ()
{ total = A+B; cout<<”\n the sum of A and B=”<<total; }
};
Difference between structure and class in C++
In C++, a structure is a class defined with the struct keyword.Its members and base classes
are public by default. A class defined with the class keyword has private members and base
classes by default. This is the only difference between structs and classes in C++.
INLINE FUNCTIONS
Inline functions definition starts with keyword inline
The compiler replaces the function call statement with the function code
itself(expansion) and then compiles the entire code.
They run little faster than normal functions as function calling overheads are saved.
A function can be declared inline by placing the keyword inline before it.
Example
inline void Square (int a)
{ cout<<a*a;
}
void main() {.
Square(4); { cout <<4*4;}
Square(8) ; { cout <<8*8; } }
In place of function call , function body is substituted because Square () is inline function.
Study Material - CS-XII Chap - 4 : Classes and Objects 5
Study Material - CS-XII Chap - 4 : Classes and Objects 5
Pass Object As An Argument
/*C++ PROGRAM TO PASS OBJECT AS AN ARGUMEMT. The program Adds the
two heights given in feet and inches. */
#include< iostream.h>
#include< conio.h>
class height
{
int feet,inches;
public:
void getht(int f,int i)
{
feet=f;
inches=i;
}
void putheight()
{
cout< < "\nHeight is:"< < feet< < "feet\t"< < inches< < "inches"< < endl;
}
void sum(height a,height b)
{
height n;
n.feet = a.feet + b.feet;
n.inches = a.inches + b.inches;
if(n.inches ==12)
{
n.feet++;
n.inches = n.inches -12;
} cout< < endl< < "Height is "< < n.feet< < " feet and "< < n.inches< < endl; }}; void main()
{height h,d,a;
clrscr();
h.getht(6,5);
a.getht(2,7);
h.putheight();
a.putheight();
d.sum(h,a);
getch();
}
/**********OUTPUT***********
Height is:6feet 5inches
Height is:2feet 7inches
Height is 9 feet and 0
Study Material - CS-XII Chap - 4 : Classes and Objects 6
Study Material - CS-XII Chap - 4 : Classes and Objects 6
Solved Problems :
Q 1) Define a class TAXPAYER in C++ with following description : Private members :
Name of type string
PanNo of type string
Taxabincm (Taxable income) of type float
TotTax of type doubleA function CompTax( ) to calculate tax according to the following slab: Taxable Income Tax%
Up to 160000 0 >160000 and <=300000 5
>300000 and <=500000 10
>500000 15 Public members :
A parameterized constructor to initialize all the members
A function INTAX( ) to enter data for the tax payer and call function CompTax( ) to assign TotTax.
A function OUTAX( ) to allow user to view the content of all the data
members.
Ans. class TAXPAYER {
char Name[30],PanNo[30];
float Taxabincm;
double TotTax;
void CompTax() { if(Taxabincm
>500000) TotTax=
Taxabincm*0.15; else
if(Taxabincm>300000)
TotTax=
Taxabincm*0.1; Else
if(Taxabincm>160000)
TotTax=
Taxabincm*0.05; else TotTax=0.0; }
public: TAXPAYER(char nm[], char pan[], float tax, double tax) //parameterized constructor {
strcpy(Name,n
m);
strcpy(PanNo,p
an);
Taxabincm=tax
; TotTax=ttax;
Study Material - CS-XII Chap - 4 : Classes and Objects 7
Study Material - CS-XII Chap - 4 : Classes and Objects 7
} void
INTAX()
{ gets(Name);
cin>>PanNo>>Taxabi
ncm; CompTax(); } void OUTAX() { cout<<Name<<‟\n‟<<PanNo<<‟\n‟<<Taxabincm<<‟\n‟<<TotTax<<endl; } }; Q 2 : Define a class HOTEL in C++ with the following description:
Private Members
Rno //Data Member to store Room No
Name //Data Member to store customer Name
Tariff //Data Member to store per day charge
NOD //Data Member to store Number of days
CALC //A function to calculate and return amount as NOD*Tariff
and if the value of NOD*Tariff is more than 10000 then as 1.05*NOD*Tariff
Public Members:
Checkin( ) //A function to enter the content RNo,Name, Tariff and NOD
Checkout() //A function to display Rno, Name, Tariff, NOD
and Amount (Amount to be displayed by calling function
CALC( )
Solution : #include<iostream.h> class HOTEL {unsigned int Rno;
char
Name[25];
unsigned int
Tariff;
unsigned int
NOD; int
CALC() {int x; x=NOD*Tariff;
if( x>10000)
return(1.05*NOD*Ta
riff);
else
return(NOD*Tariff);
}
public:
void Checkin()
{cin>>Rno>>Name>>Tariff>>NOD;}
void Checkout()
{cout<<Rno<<Name<<Tariff<<NOD<<CALC();}
Study Material - CS-XII Chap - 4 : Classes and Objects 8
Study Material - CS-XII Chap - 4 : Classes and Objects 8
};
Q 3 Define a class Applicant in C++ with following description:
Private Members A data member ANo ( Admission Number) of type long
A data member Name of type stringA data member Agg(Aggregate Marks) of type float
A data member Grade of type charA member function GradeMe( ) to find the Grade as per the Aggregate Marks obtained by a student. Equivalent Aggregate marks range and the respective Grades are shown as follows
Aggregate Marks Grade > = 80 A
Less than 80 and > = 65 B
Less than 65 and > = 50 C
Less than 50 D
Public Members
A function Enter( ) to allow user to enter values for ANo, Name, Agg & call function GradeMe( ) to find the Grade
A function Result ( ) to allow user to view the content of all the data members.
Ans: class Applicant {long ANo;
char Name[25];
float Agg;
char Grade;
void GradeMe( )
{if (Agg > = 80)
Grade = „A‟;
else if (Agg >= 65 && Agg < 80 )
Grade = „B‟;
else if (Agg >= 50 && Agg < 65 )
Grade = „C;
else
Grade = „D‟; }
public: void Enter ( ) {cout <<”\n Enter Admission No. “; cin>>ANo;
cout <<”\n Enter Name of the Applicant “; cin.getline(Name,25);
cout <<”\n Enter Aggregate Marks obtained by the Candidate :“; cin>>Agg; GradeMe( );
} void Result( ) {cout <<”\n Admission No. “<<ANo;
cout <<”\n Name of the Applicant “;<<Name;
Study Material - CS-XII Chap - 4 : Classes and Objects 9
Study Material - CS-XII Chap - 4 : Classes and Objects 9
cout<<”\n Aggregate Marks obtained by the Candidate. “ <<
Agg; cout<<\n Grade Obtained is “ << Grade ; }
};
Q.4. Define a class ITEM in C++ with following description:
Private members: Icode of type integer (Item Code)
Item of type string (Item Name)
Price of type Float (Price of each item)Qty of type integer (Quantity in stock)
Discount of type float (Discount percentage on the item)
A find function finddisc( ) to calculate discount as per the following rule:
If Qty <=50 discount is 0% If 50 < Qty <=100 discount is 5%
If Qty>100 discount is 10%
Public members :
A function Buy( ) to allow user to enter values for Icode, Item,Price, Qty and call
function Finddisc ( ) to calculate the discount. A function showall ( ) to allow user to view the content of all the data members.
Solution:-
class ITEM
{int Icode,Qty;
char item[20];
float price,discount;
void finddisc();
public:
void buy();
void showall();
};
void stock::finddisc()
{If (qty<=50)
Discount=0;
Else if (qty> 50 && qty <=100)
Discount=0.05*price;
Else if (qty>100)
Discount=0.10*price;
}
void stock::buy() {cout<<"Item Code :";cin>>Icode;
cout<<"Name :";gets(Item);
cout<<"Price :";cin>>Price;
cout<<"Quantity :";cin>>Qty;
finddisc();
}
void TEST::DISPTEST()
{cout<<"Item Code :";cout<<Icode;
cout<<"Name :";cout<<Item;
Study Material - CS-XII Chap - 4 : Classes and Objects 10
Study Material - CS-XII Chap - 4 : Classes and Objects 10
cout<<"Price :";cout<<Price;
cout<<"Quantity :";cout<<Qty;
cout<<"Discount :";cout<<discount;
}
PRACTICE QUESTIONS
Q 1. Define a class employee with the following specifications :
Private members of class employee
empno integer
ename 20 characters
basic, hra, da netpay float
calculate() A function to calculate basic + hra + da with float return type
Public member function of class employee havedata() function to accept values for empno, sname, basic, hra, da and invoke
calculate() to calculate netpay. dispdata() function to display all the data members on the screen.
Q2. Define a class Student with the following specifications :
Private members :
roll_no integer
name 20 characters
class 8 characters
marks[5] integer
percentage float
Calculate() a function that calculates overall percentage of marks and return the
percentage of marks.
public members :
Readmarks() a function that reads marks and invoke the Calculate function.
Displaymarks() a function that prints the marks.
Q3. Define a class report with the following specification :
Private members :
adno 4 digit admission number
name 20 characters
marks an array of 5 floating point values
average average marks obtained function Getavg() to compute the average obtained in five subjects
Public members :
readinfo() function to accept values for adno, name, marks, and invoke the function getavg().
displayinfo() function to display all data members on the screen you should give function definitions.
Study Material - CS-XII Chap - 4 : Classes and Objects 11
Study Material - CS-XII Chap - 4 : Classes and Objects 11
Q4. Declare a class myfolder with the following specification :
Private members of the class
Filenames – an array of strings of size[10][25]( to represent all the names of files
inside myfolder) Availspace – long ( to represent total number of bytes available in myfolder) Usedspace – long ( to represent total number of bytes used in myfolder)
Public members of the class
Newfileentry() – A function to accept values of Filenames, Availspace and
Usedspace fromuser Retavailspace() – A Fucntion that returns the value of total Kilobytes
available ( 1 Kilobytes = 1024 bytes) Showfiles() – a function that displays the names of all the files in myfolder
ASSIGNMENT
1. What is relation between class and object?
2. What are inline functions? Give example
3. Difference between private & public access specifiers.
4. How class implements data-hiding & encapsulation?
5. What is the difference between structure and a class ?
6. How is inline function different from a normal function ?
7. Rewrite the following C++ code after removing the syntax error(s) (if any). Underline each correction. include<iostream.h> class FLIGHT{ long FlightCode; char Description[25]; public: void AddInfo() { cin>>FlightCode; gets(Description); } void ShowInfo() { cout<<FlightCode<<":" <<Description<<endl; } };
Study Material - CS-XII Chap - 4 : Classes and Objects 12
Study Material - CS-XII Chap - 4 : Classes and Objects 12
void main() { FLIGHT F; AddInfo.F(); ShowInfo.F(); }
8. Rewrite the following program after removing the syntactical error(s) (if any). Underline each correction. #include[iostream.h] #include[stdio.h] class Employee { int EmpId=901; char EName[20]; public: Employee() {} void Joining() { cin>>EmpId; gets(EName); } void List() { cout<<EmpId<<":" <<EName<<endl; } } void main(){ Employee E; Joining.E(); E.List(); }
9. Identify the error(s) in the following code fragment: class X{ int a b; void count(void) { a++; } public: int x; void init(int,int,int); void print(void);
Study Material - CS-XII Chap - 4 : Classes and Objects 13
Study Material - CS-XII Chap - 4 : Classes and Objects 13
}; void X::init(int i,int j,int k){ a=i; b=j; x=k; } void X::print(void){ count(); cout<<"a="<<a;<<"b=" <<b<<"x="<<x<<"\"; } void func(void); X Ob1; int main(){ X Ob2; Ob1.init(0,1,2); Ob2.init(2,3,4); Ob1.print(); Ob2.print(); Ob1.count(); Ob2.count(); } void func(void) { X Ob3; Ob1.init(4,5,6); Ob2.init(7,8,9); Ob3.init(9,10,11); Ob3.a=Ob3.b=Ob3.x; }
10. Define a class to represent batsmen in a cricket team. Include the following members: Data Members: First name, Last name, Runs made, Number of fours, Number of sixes Member Functions: (i) To assign the initial values (ii) To update runs made (It should simultaneously update fours and sixes, if required). (iii) To display the batsman’s information Make appropriate assumptions about access labels.
11. Define a class student with the following specifications: private members of class student admno integer sname 20 characters
Study Material - CS-XII Chap - 4 : Classes and Objects 14
Study Material - CS-XII Chap - 4 : Classes and Objects 14
eng, math, science float total float ctotal() A function to calculate eng + math + science with float return type public member functions of class student Takedata() function to accept values for admno, sname, eng, math, science and ivoke ctotal() to calculate total. Showdata() function to display all the data members on the screen.
12. Declare a class to represent bank account of 10 customers with the following data members. Name of the depositor, Account number, Type of account (S for Savings and C for Current), Balance amount. The class also contains member functions to do the following: (i) To initialize data members (ii) To deposit money (iii) To withdraw money after checking the balance (minimum balance in Rs. 1000) (iv) To display the data members
13. Define a class worker with the following specification: Private members of class worker
wname 25 characters
hrwrk float (hors worked and wagerate per hour)
totwage float(hrwrk*wgrate)
calcwg A fuction to find hrerk* wgrate with float return type
Public members of class worker
in_data() a function to accept values for wno, wname, hrwrk, wgrate and invoke calcwg() to calculate totwage.
out_data() a function to display all the data members on the screen
14. Define a class Teacher with the following specification: private members:
name 20 characters
subject 10 characters
Basic,DA,HRA float
salary float
Calculate() function computes the salary and returns it. Salary is sum of Basic, DA and HRA
public members:
Readdata() function accepts the data values and invoke the calculate function
Displaydata() function prints the data on the screen.
Study Material - CS-XII Chap - 4 : Classes and Objects 15
Study Material - CS-XII Chap - 4 : Classes and Objects 15
15. Define a class Student with the following specification: private members:
roll_no integer
name 20 characters
class 8 characters
marks[5] integer
percentage float
Calculate() function that calculates overall percentage of marks and returns the percentage of marks.
public members:
Readmarks() a function that reads marks and invokes the calculate function.
Displaymarks() a function that prints the marks.
16. Write a program that invokes a function newdate() to return a object of date type. The function newdate() takes two parameters: an object olddate of date type and number of days (int) to calculate the newdate as olddate + number of days and returns the newdate.
Study Material - CS-XII Chap - 5 : Constructors & Destructors 1
CHAPTER - 5 : Constructors And Destructors
Constructors:
Constructors are member functions of a class which are used to initialize the
data members of the class objects. These functions are automatically called when an object of its class is created. There is no need to call these functions.
Characteristics of Constructors:
The name of a constructor is same as that of class in which it is declared. Constructors do not have any return type, not even void. Constructors are always defined in the public section of the class. They cannot be inherited, though a derived class can call the base class
constructor. Like other C++ functions, constructors can also be overloaded.
Types of Constructors: There are three types of constructors.
1. Default Constructors 2. Parameterized Constructors 3. Copy Constructors
Default Constructors A constructor that accepts no parameter is called the default constructors.
Example class stud { int sno;
char sname[40]; public :
stud( ) // Default Constructor {
sno=0; strcpy(sname,“new” );
} void getinfo( ) {cin>> sno;
gets(sname);
} void showinfo( ) {cout<< sno; puts(sname); }
};
BY: MOHIT TANDON PGT(CS) LPS SEC-D
Study Material - CS-XII Chap - 5 : Constructors & Destructors 2
Study Material - CS-XII Chap - 5 : Constructors & Destructors 2
The above class stud has sno and sname as data members and three member functions i.e. stud (), getinfo(), showinfo( )
Here stud ( ) is a default constructor since having the same name as that of class and does not accepts any argument, also declared in the pubic section.
As we declare the object of this class it will immediately call to the constructor of the class.It automatically assigns the value 0 to variable sno and a “new” to sname. Here consider the following main function void main() {
stud obj; // Default constructor called Obj.showinfo(); // displays the value of sno as 0 and sname as “new” Obj.getinfo(); // reads the user given value from the user Obj.showinfo(); // displays the user given values
} The default constructors are very useful when we want to create objects without having to type the initial values. With a default constructor objects are created just the same way as variables of other data types are created.
Parameterized Constructors A constructor that accepts parameters for its invocation is known as parameterized constructors. Example class stud {
Int sno; char sname[40]; public :
stud(int s, char n[ ] ) {
// Paramerized Constructor
sno=s; strcpy(sname,n);
} void getinfo( ) { cin>> sno;
gets(sname); } void showinfo( ) { cout<< sno;
puts(sname); }
}; This means we always specify the arguments whenever we declare an instance (object) of the class.
Study Material - CS-XII Chap - 5 : Constructors & Destructors 3
Study Material - CS-XII Chap - 5 : Constructors & Destructors 3
void main() {
stud obj (1, “Ashu”); // Parameterized constructor invoked Obj.showinfo(); // displays the value of sno as 1 and sname as “Ashu” Obj.getinfo(); // reads the user given value from the user Obj.showinfo(); // displays the user given values
}
Just like any other function a parameterized constructor can also have default arguments
e.g. stud(int s=0, char n[ ]=“new\0” ) A constructor with default arguments is equivalent to a default constructor. A class must not have a default arguments constructor and default constructor
together as it generates ambiguity.
Copy Constructors: A copy constructor is a constructor of the form classname( & classname). It is used to initialize an object with the values of another object.
The compiler will use the copy constructor whenever - 1. We initialize an instance using values of another instance of same type.
2. A function returns an object
3. A function receives an object as parameter. Example:
class stud
{int sno; char sname[40]; public : stud( stud &s)
// Copy Constructor
{
sno=s.sno; strcpy(sname,s.name);
} stud( )// Default Constructor { sno=0; strcpy(sname,“new” ); } void getinfo( ) { cin>> sno; gets(sname); } void showinfo( ) { cout<< sno; puts(sname); } };
Study Material - CS-XII Chap - 5 : Constructors & Destructors 4
Study Material - CS-XII Chap - 5 : Constructors & Destructors 4
void main() {
stud obj; // Default constructor called Obj.showinfo(); // displays the value of sno as 0 and sname as “new” stud objnew(obj); // Copy constructor invoked and initialize the members
of object objnew with the values of object obj i.e. 0 and “new”.
Objnew.showinfo(); //displays the value of sno as 0 and sname as “new” Obj.getinfo(); //reads the user given value for object obj Obj.showinfo(); // displays the user given values for object obj Objnew.getinfo(); // reads the user given value for object objnew Objnew.showinfo(); // displays the user given values for object objnew
} Lets have a look:
Stud obj; // default constructor used
stud obj1(23, “Nisha”);// parameterized constructor used
stud obj2 = obj; // copy constructor used
stud obj3= obj1;// copy constructor used
Points to remember: Declaring a constructor with arguments hides the default constructor.
A Constructor with default arguments is equivalent to a default constructor.
A constructor declared under private access specifier, makes the class private and
object of a private class cannot be created.
A class must not have a default arguments constructor and default constructor
together as it generates ambiguity.
Constructors also show the polymorphism as a single class can have multiple
constructors of different forms. (Also known as constructor / function
overloading.)
Destructors: A destructor is a class member function that has the same name as the constructor (and the class ) but with a ~ (tilde) in front. e.g. ~stud() ; Destructor is used to deinitialize or destroy the class objects. When an object goes out of scope, its destructor is automatically invoked to destroy the object.
Example : #include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h>
Study Material - CS-XII Chap - 5 : Constructors & Destructors 5
Study Material - CS-XII Chap - 5 : Constructors & Destructors 5
class stud { int sno;
char sname[40]; public :
stud( ) {
// Default Constructor
sno=0; strcpy(sname,"new"); cout<<"\nConstructing the object............";
} ~stud( )
{
// Destructor
cout<< "\nDestructing the object.............."; }
void getinfo( ) { cout<<"\nEnter Student No. :"; cin>> sno; cout<<"\nEnter Student Name :"; gets(sname);
} void showinfo( ) { cout<< "\n Student No.: "<<sno;
cout<<"\n Student Name :"; puts(sname);
} }; void main() { clrscr();
stud obj; // Default constructor called obj.showinfo(); // displays the value of sno as 0 and sname as “new” obj.getinfo(); // reads the user given value for object obj obj.showinfo(); // displays the user given values for object obj getch();
}
Output:
Study Material - CS-XII Chap - 5 : Constructors & Destructors 6
Study Material - CS-XII Chap - 5 : Constructors & Destructors 6
Study Material - CS-XII Chap - 5 : Constructors & Destructors 7
Study Material - CS-XII Chap - 5 : Constructors & Destructors 7
ASSIGNMENT Problem 1: Answer the questions (i) and (ii) after going through the following program:
class Match {int Time; public: Match()
//Function 1
{Time=0; cout<<”Match commences”<<end1; } void Details()
//Function 2
{ cout<<”Inter Section Basketball Match”<<end1; } Match(int Duration) //Function 3 { Time=Duration; cout<<”Another Match begins now”<<end1; } Match(Match &M)
//Function 4
{ Time=M.Duration; cout<<”Like Previous Match ”<<end1; }};
i. Which category of constructor - Function 4 belongs to and what is the purpose of using it?
ii. Write statements that would call the member Functions 1 and 3. Problem 2: What is the use of a constructor function in a class? Give a suitable
example of a constructor function in a class. Problem 3: What do you understand by default constructor and copy constructor
functions used in classes? How are these functions different form normal constructors?
Problem 4: Differentiate between default constructor and copy constructor, give
suitable examples of each. Problem 5: What is copy constructor? Give an example in C++ to illustrate copy constructor. Problem 6: Answer the questions (i) and (ii) after going through the following program:
#include <iostream.h> #include<string.h>
Study Material - CS-XII Chap - 5 : Constructors & Destructors 8
Study Material - CS-XII Chap - 5 : Constructors & Destructors 8
class Bazar { char Type[20]; char Product[20]; int Qty; float Price; Bazar( ) //Function 1
{strcpy (Type, “Electronic”); strcpy(Product, “Calculator”); Qty = 10; Price = 225; } public : void Disp( ) //Function 2 {cout << Type << “-“ << Product << “:” << Qty << ”@” << Price << endl; } }; void main( ) { Bazar B ; B. Disp( );
//Statement 1 //Statement 2
}
i. Will Statement 1 initialize all the data members for object B with the values given in the Function 1 ? (Yes OR No). Justify your answer suggesting the correction(s) to be made in the above code.(Hint: Based on the characteristics of Constructor declaration) ii. What shall be the possible output when the program gets executed? (Assuming, if required the suggested correction(s) are made in the program).
Problem 7: Answer the questions (a) and (b) after going through the following class:
class Interview { int month: public: Interview(int y) { Month=y;} Interview(Interview & t); };
1. Create an object, such that it invokes Constructor 1. 2. Write complete definition for Constructor 2.
Problem 8: Answer the questions (i) and (ii) after going through the following program:
class Match { int Time; public:
Match() //Function 1
Study Material - CS-XII Chap - 5 : Constructors & Destructors 9
Study Material - CS-XII Chap - 5 : Constructors & Destructors 9
{Time=0; cout<<”Match commences”<<endl;
} void Details() //Function 2 {cout<<”Inter Section Basketball Match”<<end1; } Match(int Duration) //Function 3 {Time=Duration;
cout<<”Another Match begins now”<<end1; }
Match(Match &M) //Function 4 {Time=M.Duration; cout<<”Like Previous Match ”<<end1; } ~Match() //Function-5 { cout<<”Match is Finished”<<endl; } void show() { cout<<time;} //Function-6
}; void main() { Match M1(90),M2; ----------------------------//Statement-1 M1.show(); M2.show(); }
i. What is Function-5 called as and when is it called? ii. Write statement-1 that would call the member Functions 4 using object
M1 defined inside main(); iii. How many times the message “Match is Finished” will be displayed
on screen?
Problem 9: What is a copy constructor? What do you understand by constructor overloading?
Problem 10: What is default constructor? How does it differ from destructor?
Problem 11: Why is a destructor function required in classes? Illustrate with the help of an example.
Problem 12: Answer the questions (i) and (ii) after going through the following class: class Science {char Topic[20]; int Weightage;
Study Material - CS-XII Chap - 5 : Constructors & Destructors 10
Study Material - CS-XII Chap - 5 : Constructors & Destructors 10
public: Science ( ) //Function 1 {strcpy (Topic, “Optics” ); Weightage = 30; cout<<“Topic Activated”;} ~Science( ) //Function 2 { cout‟<<”Topic Deactivated”; } };
(i) Name the specific features of class shown by Function 1 and Function 2 in the above example.
(ii) How would Function 1 and Function 2 get executed?
-----------------------
XII-CS-NOTES CHAPTER 6:INHERITANCE Page 1 of 7
Notes By:
NEERU NIGAM,
PGT(CS),SECTOR-I
CHAPTER 6:Inheritance:Extending Classes
It is one of the strongest property of Object Oriented Language . This
property means transiting the properties or characteristics of PARENT CLASS (
also known as BASE CLASS OR SUPER CLASS ) to its CHILD CLASS (
known as DERIVED CLASS OR SUB CLASS ).
Inheritance is the acts of deriving a new class from an existing class.
Pictorial description of Inheritance
Class derived-class name : visibility-mode base-class name
{
................
................ // members of the derived class
................
};
PARENT / BASE CLASS
CHILD / DERIVED CLASS
Inherits properties
from the base class
Inherits properties
from the base class
XII-CS-NOTES CHAPTER 6:INHERITANCE Page 2 of 7
Points to remember :-
Here transiting properties means ... transiting data members and member
functions.
Since the properties get transited into child class , hence phenomenon of
Inheritence is also known as Extending the class.
The derived class or child class is not a replica of the base class or parent
class.
The child class or derived class can have all the properties of the parent
class or base class, but it contains at least one property of its own, to
retain its identity.
All the properties of the parent class get inherited but all are not
accessible into its child class.
The accessibility of the properties of parent class into child class depends
on the Visibility mode.
Inherited variables and methods can be used in the derived class as if they
had been declared locally.
Inherited variables and methods keep their original visibility
characteristics in the subclass.
VISIBLITY MODE : In very simple words, we can say that the
restrictions applied over the data members and member functions of the
base class, for their accessibility in the derived class, is determined by
visibility mode.
Private Visibility Mode :
The variables and methods are not available to any outside calling
routines, and they are not available to any derived classes inheriting this
class. All entities are inherited as private due to use of keyword private
prior to the name of the base class. They are therefore unavailable to any
code outside the derived class.
The declaration will be :
class derived : private base
{
..............
..............
XII-CS-NOTES CHAPTER 6:INHERITANCE Page 3 of 7
}
If the data members and member functions are privately derived, then, the
following points to remember :
If the data members and member functions are private in base
class, then they cannot have access in derived class.
If the data members and member functions are public in base
class, they can have access in the derived class.
If the data members and member functions are protected in base
class, they can have access in derived class.
Public Visibility Mode :
In Public visibility mode, all variables and methods are freely
available to all outside calling routines and to all the derived classes.
The keyword public, when included prior to the base class name,
makes all the data members and member functions available for use
in the derived class.
The declaration will be :
class derived : public base
{
...................
.................
};
If the data members and member functions are publicly derived, then,
remember the following :
If the data members and member functions are private in
base class, then they cannot have access in derived class.
If the data members and member functions are public in base
class, then they can have access in derived class.
XII-CS-NOTES CHAPTER 6:INHERITANCE Page 4 of 7
If the data members and member functions are protected in
base class, they can have access in derived class as public
members of derived class but outside the derived class they
become private.
Protected Visibility Mode : Protected members are just like private
members except that they are accessible to the member functions of derived
classes. The variables and methods are not available to any outside calling
routines, but they are directly available to any derived class inheriting this class.
The elements are inherited into the derived class such that they are at the same
level of protection they had in the base class.
The declaration will be :
class derived : protected base
{
..................
....................
}
SUMMARY
A private member is accessible only to members of the class in
which the private member is declared.
A protected member is accessible to members of its own class and
to any members in a derived class.
A public member is accessible to th class’s own members, to a
derived class’s members and to all other users of the class.
XII-CS-NOTES CHAPTER 6:INHERITANCE Page 5 of 7
Types of Inheritance
1. Single Inheritance : A derived class with only one base class
is called single inheritance.
2. Multilevel Inheritance : In this type of inheritance , the
derived class becomes the base class for its lower level of class.
Base class
Intermediate Base Class
3. Hierarchical Inheritance
In this type of inheritance, more than one derived classes can
be derived from one base class.
BASE / PARENT CLASS
DERIVED / CHILD CLASS
CLASS A
CLASS B
CLASS C
XII-CS-NOTES CHAPTER 6:INHERITANCE Page 6 of 7
4. Multiple Inheritance : In this type of inheritance , one class
can be derived from more than one base classes.
Containership : This means that one class is being contained in other class
i.e, the object of one class is being declared as one of the member of another
class. Such classes are known as nested classes and this relationship is known as
containership.
EMPLOYEES
PRIVATE GOVERNMENT DAILY-WAGE
PERMANANT CONTRACTUAL
BASE CLASS A BASE CLASS B BASE CLASS C
DERIVED CLASS
XII-CS-NOTES CHAPTER 6:INHERITANCE Page 7 of 7
Important points
The order of invocation of constructor in case of inheritance.. constructor
of base class constructor of derived class
The order of invocation of destructor in case of inheritance..
Destructor of derived class destructor of base class
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 1 of 38
Chapter 7: Data File Handling
Basics of file Handling
File: A file is just a bunch of bytes stored on some storage devices like hard disk, pen drive etc. Some
have a specific structure others don‟t. Files are used to save info so that it can be retrieved later for use.
File can be a c++program file, a data file, document file etc. Every device is represented by a specific file
in computer system.
Need file handling:
When a program is terminated, the program data stored in main memory is lost. To store data
permanently, you need to write that data to a file on an external storage medium.
Stream: We can think of a stream as a sequence of bytes(data) passing from senders(file) to
receivers(file). Data can be sent out from the program to devices through memory, or received into the
program from devices through memory.
For example, at the start of a program, the standard input stream “cin” is connected to the keyboard and
the standard output stream “cout” is connected to the screen.
Types of streams.
Output stream:
The stream that sends data from c++program to a data file on output device. It is one way data
flow.
Output stream
Input stream:
The stream that receives or read data from a file on device and supply it to the c++ program. It is
one way data flow.
Input stream
Input/ Output streams:
The stream that sends/receives data from c++ program to/from file on device. it is two way data
flow.
Output Input stream
Types of Files processed by c++ program.
Generally there are two types of files in C++:
Text Files: A text file is usually considered as sequence of lines. Line is a sequence of characters
stored on permanent storage media. Each line is terminated by a special character, known as End
C++ program memory File(output Device)
C++ program memory File(input Device)
C++ program memory File(Input/Output Device)
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 2 of 38
of Line (EOL).Stores information in ASCII characters. In text file some translations takes place
when this EOL character is read or written.
Binary Files: Data is stored in binary form or in machine language. This data is in non-readable
form.it contains the information in the same format as it is held in the memory. In binary file there
is no delimiter for a line. Also no translation occur in binary file as a result binary files are faster
and easier for program to read and write.
Steps involved to open a data file and process it .
Step 1: Create an object of respective type of stream(input/output stream type).
Step2: Open the data file for reading/ writing or both using the object created in step 1.
Step 3: Read /write contents from/to the data file using the object.
Step 4: Close the data file.
//keep in mind the above steps are always used for data file handling
Classes required for Data File Handling operations in c++.
There are three file I/O classes used for file read / write operations.
ifstream
ifstream
fstream
1. ifstream – It provides functions to Open the already existed data file for Input and read its contents
into c++ program. Data file is opened for reading purpose only.
An object of ifstream class is to be created in the program to carry out reading operations
from the data file.
Example.
ifstream p; // statement to create object of ifstream class
Here p is the object of ifstream that will carry out respective reading operations through available
function of ifstream class.
2. ofstream – It provides functions to Open the data file for writing purpose and write or add contents
to that file from c++ program. Data file is opened for writing purpose only.
An object of ofstream class is to be created in the program to carry out writing operations
from the data file
Example.
ofstream p; // statement to create object of ofstream class
Here p is the object of ofstream that will carry out respective writing operations through available
function of ofstream class.
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 3 of 38
3. fstream – it provides functions to Open the data file (Open the file for Input /Output /both) and both
read & write operations can be done.
Data file is opened for reading /writing or both purpose.
An object of fstream class is to be created in the program to carry out reading/ writing operations
Example.
fstream p;// statement to create object of fstream class
Here p is the object of fstream that will carry out respective reading /writing operations through
available function of fstream class.
Role of fstream.h header file.
fstream.h: This header file includes the definitions for the stream classes ifstream, ofstream and fstream.
In C++ file input output facilities implemented through fstream.h header file. It contains
predefined set of operation for handling file related input and output, fstream class ties a file to
the program for input and output operation.
Methods to open a data file in c++ program.
A file in C++ can be opened in the following two ways-
1. By the constructor method. The constructors of a stream classes (ifstream, ofstream, or fstream) are
used to initialize the file stream objects with the file names passed to them. This method is preferred
when file is opened in input or output mode only.
Example:
ifstream fin(“datafilename”); //to open file in input mode for reading only
ofstream fout(“datafilename”);//to open file in output mode for writing only
fstream fio(“datafilename”); //to open file in input mode for reading & writing both purpose
2. By using the open( ) member function of the streams-
It will be preferred in when file is opened in various modes i.e. ios::in, ios:out, ios::app etc. It is also
used while working with two or more files in a program.
Streamtype objectname;// Streamtype can be ifstream or ofstream or fstream class name.
objectname.open(“datafilename”,filemode);//filemode can be input or output etc.
Example:
ifstream P;//object of input stream class type
p.open(“abc.txt”,ios::in);//abc.txt is file name that is opened in reading mode only.
Closing a File:
A file is closed by disconnecting it with the stream it is associated with. The close() function is used to
close an opened file.
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 4 of 38
Syntax:
stream_object.close( );
out_stream.close(); //out_stream is stream object
//sample program to write a sentence in a text file through c++
#include<fstream.h> // To carry out file handling operations using existing classes
void main( )
{
//Step 1: Create an object of respective of type of stream(input/output stream type).
ofstream Fout; //Fout object will be used to carry out writing to text file
//Step2: Open the data file using the object Fout
Fout.open(“abc.txt”,ios::out); //abc.txt is open for writing purpose only
//Step 3: Read /write contents from/to the data file using the object Fout.
Fout<<”focus and attention are key to success”;
//Step 4: Close the data file.
Fout.close( );
}
//we will understand the above code and more details of data file handling in the following
pages.
FILE MODES
The file mode describes how a file is to be used: to read it, to write it, to append it, and so on. File mode
is used with open() of the stream class.
Syntax:
stream_object.open(“filename”, filemode);
File mode
constants
Purpose Stream type
ios::out It open file in output mode i.e write mode and place the file pointer
in beginning, if file already exist it will overwrite the file. ofstream
ios::in It open file in input mode i.e. read mode and permit reading from the
file. ifstream
ios::app It open the file in write mode, and place file pointer at the end of file
i.e to add new contents and retains previous contents. If file does not
exist it will create a new file.
ofstream
ios::ate It open the file in write or read mode, and place file pointer at the
end of file.But position of file pointer can be changed. ofstream
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 5 of 38
ios::trunc If the file is opened for output operations and is already existed, its
previous content is deleted and replaced by the new one. ofstream
ios::nocreate If file does not exist this file mode ensures that no file is created and
open fails. ofstream
ios::noreplace If file does not exist, a new file gets created but if the file already
exists, the open fails. Ofstream
ios::binary Opens a file in binary mode. ofstream,
ifstream
The default mode is text mode when a file is opened.
All these filemodes can be combined using the bitwise operator OR (|). For example, if we want to open
the file “example.bin” in binary mode to add data we could do it by the following call to member
function open:
ofstream myfile;
myfile.open (“example.dat”, 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
Detecting end of file :
using eof():
It is used to know the end of data file.it returns a non-zero integer if the end of file is met otherwise it
returns zero.
ifstream P;
P.open(“abc.txt”,ios::in);
while(!P.eof( ))
{
//Code to read and process
.}
//alternate way to check end of file
ifstream P;
P.open(“abc.txt”,ios::in);
while(P) // P becomes NULL at the end of file i.e no valid data
{
//Code to read and process
.}
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 6 of 38
WORKING WITH TEXT FILE
Methods for writing in a text file.
1. put( ) – This function is used for writing a single character in file.
file1.put(„c‟);
2. Insertion operator (<<) – This operator is also used to write in a file.
file1<<”work is worship”;
Steps involved in creating a text file and adding text to a text file using put( ).
1. Create object of ofstream class.
ofstream file1;
2. Open a file with this object.
file1.open (“names.txt”,ios::out );
3. Write in the file (add two line of text)
file1.put(„a‟);//it will write „a‟ to the file
file1.put(„b‟);// it will write „b‟ to the file just after „a‟
4. Close the opened file using close() function.
file1.close();
// A Simple example to write data in a text file using put( )
#include <fstream.h>
void main()
{
ofstream File1;
File1.open("names.txt", ios::out);// it will create a new file or overwrite the file
File1.put(„a‟);//it will write „a‟ to the file
File1.put(„b‟);// it will write „b‟ to the file just after „a‟
File1.close();
}
Steps involved in creating a text file and adding text to a text file( insertion operator<<).
1. Create object of ofstream class.
ofstream file1;
2. Open a file with this object.
file1.open (“names.txt”,ios::out );
3. Write in the file (add two line of text)
file1<<”work is worship”<<endl;// use of insertion operator to send data to text file
File1<<”life is to work”<<endl;
4. Close the opened file using close() function.
file1.close();
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 7 of 38
// A Simple example to write data in a text file using <<(insertion operator)
#include <fstream.h>
void main()
{
ofstream file1;
file1.open("names.txt", ios::out);
file1<<”work is worship”<<endl;
file1<<”life is to work”<<endl;
file1.close();
}
Steps involved to open an existing text file and adding text at the end of file. (appending data)
1. Create object of ofstream class.
ofstream file1;
2. Open a file with this object.
file1.open (“names.txt”,ios::app );//open file in append mode
3. Write in the file (add two line of text)
file1<<”revise daily”<<endl;// use of insertion operator to send data to text file
File1<<”it is important”<<endl;
4. Close the opened file using close() function.
file1.close();
// Simple example to append or add data at end of a text file
#include <fstream.h>
void main()
{
ofstream File1;
File1.open("names.txt", ios::app);
File1<<”revise daily”<<endl;// use of insertion operator to send data to text file
File1<<”it is important”<<endl;
File1.close();
}
Different methods for writing in a text file.
1. getline()- It reads characters from input stream and puts them in the array pointed to by the buff until
either num charcters have been read, or character specified by delim is encountered. If not mentioned,
the default value of delim is newline character.
Syntax:
istream & getline(char * buf, int num, char delim=‟\n‟)
char arr[20];
fileInput.getline(arr, 20); //it breaks as newline character is encountered
or
fileInput.getline(arr, 20, „$‟); //it breaks as „$‟ is encountered
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 8 of 38
2. Extraction operator (>>)- This operator is also used to read from a file.It is suitable for reading
word by word as >> cannot read whitespaces.
char arr[20];
fileInput >>arr; //where fileinput is an ifstream object
3. get( ) – This function is used for reading a single character or a string in a file.
fileInput.get(„c‟);//where fileinput is an ifstream object
or
char arr[10];
fileInput.get(arr, 10 );
Steps involved in reading line by line from a text file using getline( ).
1. Create object of ifstream class.
ifstream fileInput;
2. Open a file with this object.
fileInput.open (“names.txt” ,ios::in);
3. Read from the file (line by line)
char arr[20]; // declare an array to store the line of text
while(!fileInput.eof()) //loop to read all the data line by line till the end of file
{
fileInput.getline(arr,20); //read a line of text and storing in arr array.
cout<<arr; // display it on screen
}
4. Close the opened file using close() function.
fileInput.close( );
Example program:
// Simple example to read line by line from a text file from a file
#include <fstream.h>
void main()
{
ifstream fileInput;
fileInput.open(“names.txt,ios::in);
char arr[20];
while(!fileInput.eof()) //loop to read all the data line by line til the end of file
{
fileInput.getline(arr,20); //read a line of text and storing in arr array.
cout<<arr; // display it on screen
}
fileInput.close();
}
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 9 of 38
Steps involved in reading word by word from a text file using >> operator.
1. Create object of ifstream class.
ifstream fileInput;
2. Open a file with this object.
fileInput.open (“names.txt” ,ios::in);
3. Read from the file (line by line)
char arr[20]; //declare an array to store a word
while(!fileInput.eof()) //loop to read all the data line by line til the end of file
{
fileInput>>arr; //read a word and storing in arr array.
cout<<arr; // display it on screen
}
4. Close the opened file using close() function.
fileInput.close();
Example program:
// Simple example to read word by word from a text file from a file
#include <fstream.h>
void main()
{
ifstream fileInput;
fileInput.open(“names.txt”,ios::in);
char arr[20];
while(!fileInput.eof( )) //loop to read all the data line by line till the end of file
{
fileInput>>arr; //read a word and storing in arr array.
cout<<arr; // display it on screen
}
fileInput.close();
}
Steps involved in reading character by character from a text file using get() function.
1. Create object of ifstream class.
ifstream fileInput;
2. Open a file with this object.
fileInput.open (“names.txt” ,ios::in);
3. Read from the file (line by line)
char ch;
while(!fileInput.eof()) //loop to read all the data till the end of file
{
fileInput.get(ch); //read a character and storing in ch variable.
cout<<ch; // display it on screen
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 10 of 38
}
4. Close the opened file using close( ) function.
fileInput.close();
Example program:
// Simple example to read character by character from a text file
#include <fstream.h>
void main()
{
ifstream fileInput;
Fileinput.open(“names.txt”,ios::in);
char ch; // variable to hold a character
while(!fileInput.eof()) //loop to read all the data line by line till the end of file
{
fileInput.get(ch); //read a character and storing in ch variable.
cout<<ch; // display it on screen
}
fileInput.close();
}
SOLVED EXERCISES:
Q1. To create a File to store a string in it.
#include<fstream.h>
#include<stdio.h>
int main( )
{
char str[100];
ofstream out_obj("FileInput.txt");
cout<<"Enter Text: ";
gets(str);
cout_obj<<str;
out_obj.close();
}
Q2. Write a function in C++ to count the number of lowercase alphabets present in a text file
“BOOK.txt”.
#include<fstream.h>
#include<ctype.h>
int main()
{
char ch; int c=0;
ifstream input(“BOOK.txt”);
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 11 of 38
while(!eof())
{
input.get(ch)
if(islower(ch))
c++;
}
input.close();
cout<<”No. of lowercase alphabets: ”<<c<<endl;
}
Q3. Write a function in C++ to read the content of a text file “DELHI.TXT” and display all those
lines on screen, which are either starting with „D‟ or starting with „M‟.
#include<fstream.h>
void fun()
{
char str[100];
ifstream in("ABC.txt");
while(!in.eof())
{
in.getline(str,100))
if(str[0]=='M'||str[0]=='D')
cout<<str<<endl;
}
in.close();
}
Q4.To copy the contents of a file “names.txt” into another file “new.txt”
#include <fstream.h>
void main()
{
ifstream fileInput;
ofstream fileout;
fileinput.open(“names.txt”,ios::in); // open source file in input mode or reading mode
fileout.open(“new.txt”,ios::out); // open destination file in output mode or writing mode
char ch[80];
while(!fileInput.eof( )) //loop to read all the data line by line till the end of file
{
fileInput.getline(ch,80); //read a charcter from names.txt and storing in ch variable.
fileout <<ch; // writing ch data to new.txt
}
fileInput.close();
fileout.close();}
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 12 of 38
WORKING WITH BINARY FILES
Binary file are suitable to write data of object type like structure or class
Example : records of students, records of persons etc
So we will focus on storing and manipulation records represented by a structure or a class only .
Basic operation done on binary file:
Create a new file and storing data in it
Appending data to an existing file
Reading data from binary file
Searching data in a binary file
Insert data in a binary file
Delete data from binary file
Modify data in a binary file
Opening a file in binary mode:
The operations we have learnt so far are also applicable on binary files. But in case of binary files we will
use the ios::binary file mode while opening a file.
Example of opening a binary file:
int main()
{
ifstream infile;
infile.open("hello.dat", ios::binary | ios::in);//open the file “hello.dat” in binary mode
// rest of program
}
Writing to a binary file:
The ofstream class provides a member function named write( ) that allows for information to be written
in binary form to the stream. The prototype of the write function is
ostream& write((char *)&object, int sizeof(object));
here object can be a structure or a class object,binary file is suitable to maintain record type of
data
This function will write a block of binary data or writes fixed number of bytes from a specific memory
location to the specified stream and moves the file pointer ahead by sizeof(object) bytes.
File Pointer: The file pointer indicates the position in the file at which the next input/output is to
occur.
Create a new file and storing data in it
Example: let us store information of two persons represented by following structure:
struct Person
{
char name[50];
int age;
char gender[10];
};
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 13 of 38
void main( ){
Person P1 = {"SAM", 18, "male"};
Person P2 = {"Soma", 17, "female"};
ofstream outfile;
outfile.open("PERSON.dat", ios::binary | ios::out);
outfile.write((char *)&P1, sizeof(P1)); //it will write 62 bytes of person P1 data from
//beginning of file “PESON.dat”
outfile.write((char *)&P2, sizeof(P2)); // it will write 62 bytes of person P2 data after P1 data
outfile.close();
}
// The person.dat will store the following information in the form as record is represented in memory
but we can visualize in following form i.e record by record
SAM 18 male 62 bytes every record will store 62 bytes as size of object of Person is 62 bytes
Soma 17 female 124 bytes so files stores 124 bytes of data
Example:To add 10 records using a loop:
#include<fstream.h>
#include<stdio.h>
struct Person{
char name[50];
int age;
char gender[10];
};
void main( )
{
Person P;//for holding record of a person
ofstream outfile;
outfile.open("PERSON.dat", ios::binary | ios::out);
for(int i-1;i<=10;++)
{
//enter data for person p
gets(P.name);
cin>>P.age;
gets(P.gender);
//Now write or send information of P to “PERSON.dat”
outfile.write((char *)&P1, sizeof(P1)); //it will write 62 bytes of person P data
}
outfile.close();
}
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 14 of 38
Reading from a Binary File
Reading data from a binary file is just like writing it except that the function now called is read() instead
of write( ).
istream& read((char *) & object, int sizeof(object));
Here object represents the name of structure or class object
The read() function reads sizeof(object) bytes from the associated stream and puts them in the memory
pointed to by object.
// Reading single record from PERSON.dat”:
struct Person
{
char name[50];
int age;
char gender[10]; };
int main()
{
Person obj1;
ifstream inpfile;
inpfile.open("PERSON.dat", ios::binary | ios::in);
inpfile.read((char *)&obj1, sizeof(obj1)); //read first record and places it in object obj1
cout<<obj1.age<<”\t”<<obj1.name<<”\t”<<obj1.gender <<endl;
inpfile.close();
}
Reading all the content of PERSON.dat” record by record:
struct Person{
char name[50];
int age;
char gender[10]; };
void main()
{
Person obj1;
ifstream inpfile;
inpfile.open("PERSON.dat", ios::binary | ios::in);
while(inpfile.read((char *)&obj1, sizeof(Person))) //read record one by one till end of file
{
//display data of obj1 object on screen
cout<<obj1.age<<”\t”<<obj1.name<<”\t”<<obj1.gender <<endl;
}
inpfile.close( );
}
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 15 of 38
Exercises: Now solve the following questions for practice
Q1.Write a program to store 5 records of student in the binary file “student.dat” where each student is
represented by following structure.
struct student
{
int rn; //rollnumber
char name[80];
float per; //percentage
};
Q2.Write a program to read the binary file “student.dat” and count the number of students scoring above
90% ,where each student is represented by following structure.
struct student
{
int rn; //rollnumber
char name[80];
float per; //percentage
};
Q3.Write a program to read the binary file “student.dat” and copy the information students to a new file
“alpha.dat” where percentage if below 33%. Each student is represented by following structure
struct student
{
int rn; //rollnumber
char name[80];
float per; //percentage
};
Appending data to a binary file:
struct Person{
char name[50];
int age;
char gender[10];
};
void main(){
Person P = {"SAM", 18, "male"};
ofstream outfile;
outfile.open("PERSON.dat", ios::binary | ios::app);//it opens a file and put the writing
//pointer at end of file
outfile.write((char *)&P, sizeof(P)); //it will write 62 bytes of person P data at end of file
outfile.close();
}
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 16 of 38
Searching in a Binary File
#include<fstream.h>
struct Student
{
int roll;
char name[80];
};
int main()
{
Student s2;
ifstream ip_file;
ip_file.open("File1.dat", ios::binary|ios::in);
int no;
cout<<"\nEnter roll no for Searching: ";
cin>>no;
int flag=0;
while(ip_file.read((char *)&s2, sizeof(s2)))
{
if(no==s2.roll)
{
flag=1;
break;
}
}
if(flag==1)
cout<<"\nRoll found.";
else
cout<<"\nRoll Not found!";
ip_file.close();
}
Insert a record at a certain position in a binary file: The process requires reading data from source file and copying data to a temporary data file along
with new data to be inserted.
Temporary file contains the updated data
Delete the source file and rename the temporary as source file.
step1 : create the input stream object and two record objects
student obj1,obj2={11,”anand”};
ifstream fin;
step 2:open the file by using stream object
fin.open(“file.dat”,ios::binary|ios::in);
step 3: create an output stream object and open the file “temp.dat”
ofstream fout;
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 17 of 38
fout.open(“temp.dat”,ios::binary|ios::ios::out);// to hold the updated data
step 4:read the record one by one from “file.dat”
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn==3)// inserting at 3
{
fout.write((char*)&obj2,sizeof(obj2));//insert before roll no 3 by copying it before 3 to
temp.dat
fout.write((char*)&obj1,sizeof(obj1));//copying current record obj1 after obj2
}
fout.write((char*)&obj1,sizeof(obj1));//copying current record obj1
}
Step 5: Close both the files
fin.close( );
fout.close( );
Step 6: Delete the original file “file.dat”
remove(“file.dat”); //statement to remove a file
Step 7: Rename the “temp.dat” to “file.dat” as temp.dat stores is the updated file
rename(“temp.dat”,”file.dat”); //statement to rename a file
Program for insertion of record at a certain place
#include<fstream.h>
struct Student
{
int roll;
char name[80];
};
void main( )
{
Student obj1,obj2={11,”anand”};
ifstream fin;
fin.open(“file.dat”,ios::binary|ios::in);
ofstream fout;
fout.open(“temp.dat”,ios::binary|ios::ios::out);
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn==3)
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 18 of 38
{
fout.write((char*)&obj2,sizeof(obj2));//insert before roll no 3 by copying it before 3 to temp.dat
}
fout.write((char*)&obj1,sizeof(obj1)); //copying current record obj1 to temp.dat
}
fin.close( );
fout.close( );
remove(“file.dat”); //statement to remove a file
rename(“temp.dat”,”file.dat”); //statement to rename a file
}
Delete a record from a binary file The process requires reading data from source file and copying all the record to a temporary data
except the record to be deleted.
Temporary file contains the updated data
Delete the source file and rename the temporary as source file.
step1 : create the input stream object and a record object
student obj1;
ifstream fin;
step 2:open the file by using object
fin.open(“file.dat”,ios::binary|ios::in);
step 3: create an output stream object and open the “temp.dat” file
ofstream fout;
fout.open(“temp.dat”,ios::binary|ios::ios::out);
step 4:read the record one by one from “file.dat”
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn!=11) // delete roll no 11 by not copying to temp.dat
fout.write((char*)&obj1,sizeof(obj1));//copying current record except 11 roll no
}
Step 5: Close both the files
fin.close( );
fout.close( );
Step 6: Delete the original file “file.dat”
remove(“file.dat”);//statement to remove a file
Step 7: Rename the “temp.dat” to “file.dat” as temp.dat stores is the updated file
rename(“temp.dat”,”file.dat”);//statement to rename a file
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 19 of 38
Program for deletion of a record
#include<fstream.h>
struct Student
{
int roll;
char name[80];
};
void main( )
{
student obj1,obj2={11,”anand”};
ifstream fin;
fin.open(“file.dat”,ios::binary|ios::in);
ofstream fout;
fout.open(“temp.dat”,ios::binary|ios::ios::out);
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn!=11) // delete roll no 11 by not copying to temp.dat
fout.write((char*)&obj1,sizeof(obj1));//copying current record except 11 roll no
}
fin.close( );
fout.close( );
remove(“file.dat”);//statement to remove a file
rename(“temp.dat”,”file.dat”);//statement to rename a file
}
Random file access functions and file pointers:
Each stream has internally two pointers to represent the reading and writing location.
These are said as get pointer and put pointer.
write( ): it writes the record and moves the position of put pointer forward by one record.
read( ): it reads the record and moves the get pointer forward one record by one record.
To manipulate position of get pointer and pointer following functions are used:
seekg( ): it is used to change position of get pointer i.e forward or backward before reading data
randomly from any location in a file.it is used with ifstream and fstream
seekp( ): it is used to change position of put pointer i.e forward or backward before writing data
randomly from any location in a file. it is used with ofstream and fstream
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 20 of 38
Unserstanding seekg( ) and seekp( ):
Syntax:
Stream_object.seekg(offset,refposition);
Stream_object.seekg(offset); //refposition will be set from beginning of file
Stream_object.seekp(offset,refposition);
Stream_object.seekp(offset); //refposition will be set from beginning of file
Here offset is distance in bytes( it is in long integer in turbo c++) from refposition.
refpoistion: it represents the start point of changing position of file pointer
refposition is represented by following constants:
ios::beg – refposition will be from start of file.( default type)
ios::cur – refposition will be from current position of get pointer.
ios::end – refposition will be from end of file
Example: To change position of get pointer using seekg ()
struct student
{
int rn;
char name[80];
};
void main()
{
ifstream Fin;
Fin.seekg(0); // it will move the position to beginning of file
Fin.seekg(sizeof(student)*5,ios::beg);//it will reposition get pointer to the end of 5th
record or
//beginning of 6th
record
Fin.seekg(-5*sizeof(student),ios::end);//it will reposition get pointer to 5 record back from end of file
Fin.seekg(0); //it takes get pointer to the end of file
Fin.seekg(-1L*sizeof(student),ios::cur); //takes to beginning of current record(82 bytes back)
}
Example: To change position of get pointer using seekp ()
struct student
{
int rn;
char name[80];
};
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 21 of 38
void main()
{
ofstream File;
File.seekp(0);// it will move the position to beginning of file
File.seekp(sizeof(student)*5,ios::beg);//it will reposition get pointer to the end of 5th
record or
//beginning of 6th
record
File.seekp(-5*sizeof(student),ios::end);//it will reposition get pointer to 5 record back from end of file
File.seekp(0,ios::end); //it takes get pointer to the end of file
File.seekp(-1L*sizeof(student),ios::cur); //takes to beginning of current record(82 bytes back)
}
Knowing the position of get pointer:
tellg( ): it returns the location of get pointer in bytes(integer).It is used with respect to input stream.
Syntax:
streamObject.tellg( )
ifstream File;
File.seekg(0); // it will move the position to beginning of file
int pos=File.tellg( ); // pos will store 0
Knowing the position of put pointer:
tellp( ): //it returns the location of put pointer in bytes(integer)
ofstream File;
File.seekp(0); // it will move the position to beginning of file
int pos=File.tellp( ); // pos will store 0
Exercises:
Q1.A binary file stores records of 100 students where each student have following structure:
struct student
{
int rn;
char name[80];
};
i) Now give the output of following statements:
Student T;
ifstream fin;
Fin.open(“student.dat”,ios::binary | ios::in);
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 22 of 38
Fin.read((char*)&T,sizeof(T));
Fin.read((char*)&T,sizeof(T));
cout<<fin.tellg( )<<endl;
Fin.seekg(12*sizeof(T));
cout<<Fin.tellg()<<endl;
Fin.seekg(-5L*sizeof(T),ios::cur);
cout<<Fin.tellg( );
Fin.seekg(0,ios::end);
cout<<fin.tellg()/(sizeof(T)*2);
ii) Now give the output of following statements:
Student T={2”aman”};
ofstream fin;
Fin.open(“student.dat”,ios::binary | ios::out);
Fin.write((char*)&T,sizeof(T));
Fin.write((char*)&T,sizeof(T));
cout<<fin.tellp( )<<endl;
Fin.seekp(6*sizeof(T),ios::beg);
cout<<Fin.tellp()<<endl;
Fin.seekp(-1L*sizeof(T),ios::cur);
cout<<Fin.tellp( );
Fin.seekp(0,ios::end);
cout<<Fin.tellp()/sizeof(T);
Fin.seekp(0);
cout<<Fin.tellp();
Modification of record in a binary file.
fstream : fstream class provides reading and writing operation simultaneously so modification of records
is done through fstream class.
Steps involved:
step1 : create the fstream stream object
fstream fin;
step 2:open the file by using object
fin.open(“file.dat”,ios::binary|ios::in|ios::out);// open file in input and output modes
step 3: create object of given structure to hold record
student obj1;// holding record of data file
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 23 of 38
step 4:read the record one by one from “file.dat”
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn==11) // modify record having roll no 11
{ //if found move to the beginning of current record
Fin.seekg(-1L*sizeof(obj1),ios::cur);
//modify the record
Obj1.rn=111;
strcpy(obj1.name,”mohan”);
//rewriting record to binary file
fout.write((char*)&obj1,sizeof(obj1)); //it will modify the record
}
Step 5: Close both the files
fin.close( );
fout.close( );
Complete program of above steps for record modification:
#include<fstream.h>
#include<string.h>
struct student
{
int rn;
char name[80];
};
void main()
{
fstream fin;
fin.open(“file.dat”,ios::binary|ios::in|ios::out); // open file in input and output modes
student obj1; // holding record of data file
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn==11) // modify record having roll no 11
{ //if found move to the beginning of current record
Fin.seekg(-1L*sizeof(obj1),ios::cur); //L is long integer
obj1.rn=111; //modify the record
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 24 of 38
strcpy(obj1.name,”mohan”);
//rewriting record to binary file
fout.write((char*)&obj1,sizeof(obj1));//it will modify the record
}
fin.close( );
fout.close( );
}
Exercise:
Q1.Write a program to create a binary file “scholar.dat” and store 5 records of scholar
And carry out following file operation using a menu bases options
Define a function to append a scholar at the end of file
Define a function to accept any name and search it if found display its information
Define a function to accept a scholar and a name , search the name if found insert the scholar after
that record
Define a function to accept a name and delete the scholar having that name
Define a function to increase the scholar per% by 5 where per% is between 28 to 32.
Define a function to display all the scholar information on screen
READING AND WRITING CLASS OBJECTS
Like structure object read( ) and write ( ) are used to read and write class objects as a single unit.
Only data members are written to disk not the member functions.
Example:
#include<fstream.h>
#include<stdio.h>
class doctor
{
int doc_id;
char dname[80];
float salary;
public:
void enter()
{
cin>>doc_id;
gets(dname);
cin>>salary;
}
void disp()
{
cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl;
}
};
void WRITE( )//function to write data to “doctor.dat” file
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 25 of 38
{
Doctor obj;
Ofstream T;
T.open(“doctor.dat”,ios::binary|ios::out);
for(int i=1;i<=4;i++)//
{
obj.enter( ); //calling public member function to initialize private data members
T.write((char*)&obj,sizeof(obj)); //write record containing through obj object
}
T.close();
}
void APP( ) // to add record at end of file
{
Doctor obj;
Ofstream T;
T.open(“doctor.dat”,ios::binary|ios::app);
obj.enter();
T.write((char*)&obj,sizeof(obj));
T.close( );
}
void READ( )
{ Doctor obj;
ifstream T;
T.open(“doctor.dat”,ios::binary|ios::in);
while(T.read((char*)&obj,sizeof(obj)))//loop breaks if no valid data left i.e T becomes null
{
obj.disp();//calling public member function to display private data members
}
T.close();
}
void main( )
{WRITE( ); //calling function to write data
READ( ); // calling function to read and display data on screen
APP( ); //calling function to add a record at end of file
}
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 26 of 38
Chapter 7 : Data File Handling
ASSIGNMENTS
Q1 Name the header file required to carry out data file operations.
Q2 Explain the difference between binary file and text file.
Q3 Give difference between : I. ios::in and ios::out
II. ios::app and ios::ate
Q4 Give difference between get( ) and getline( ).
Q5 Give difference between seekg( ) and tellg( ).
Q6 Write statements at the given places for pre-existing binary file ”abc.dat” that stores records of items as per following information in the . struct item { int code; char name[80]; }; fstream FIT; __________________________//to open the file in I/O mode __________________________//to move to beginning of 2nd last record _____________________________// to move to beginning of file _______________________________//to display the byte number
Q7 Define a function to create a text file “os.txt” and store name of 6 operating systems in it.
Q8 Define a function to add two more operating system names in “os.txt”.
Q9 Define a function read “os.txt” file and return the number of operating systems that starts with “win”.
Q10 Define a function read “os.txt” file and return the number of upper case vowels.
Q11 Define a function read “os.txt” file and return the number of words having odd number of characters
Q12 Define a function read “os.txt” file and return the number of lines that starts with letter ‘A’.
Q13 Define a function read “os.txt” file and print the average length of line.
Q14 Define a function read “os.txt” file and print the word with maximum number of characters.
Q15 Define a function read “os.txt” file and copy all upper case alphabets to “upper.txt” and all lower case letters to “lower.txt”
Q16 Define a function create a binary file “doc.dat”and store 5 records where each record is having following structure: class doctor { int doc_id; char dname[80]; float salary; public:
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 27 of 38
void enter() { cin>>doc_id; gets(dname); cin>>salary; } void disp() { cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl; } };
Q17 Define a function open binary file “doc.dat” and append 2 records where each record is having following structure: class doctor { int doc_id; char dname[80]; long salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } void disp() { cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl; } };
Q18 Define a function read the binary file “doc.dat” and count the doctors where salary is in the range 120000-300000 and where each doctor is defined by the following class. class doctor { int doc_id; char dname[80]; long salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } long rt_sal(){return salary;} void disp()
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 28 of 38
{ cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl; } };
Q19 Define a function to read the binary file “doc.dat” copy all the doctors to file “elite.dat” where specialisation is in “radiologist”. class doctor { int doc_id; char dname[80]; char spl[80]; //type of specialisation float salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } int check(char a[]) { return strcmpi(a,spl); } void disp() { cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl; } };
Q20 Define a function open the binary file “doc.dat” and delete information of those doctors where specialisation is either “neuro” or “gastro”. class doctor { int doc_id; char dname[80]; char spl[80]; //type of specialisation float salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } char *rt_name() { return name;
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 29 of 38
} void disp() { cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl; } };
Q21 Define a function open the binary file “doc.dat” and insert a new doctor information at 3rd place from beginning. class doctor { int doc_id; char dname[80]; char spl[80]; //type of specialisation float salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } void disp() { cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl; } };
Q22 Define a function open the binary file “doc.dat” increase the salary of those doctors by 20% where specialisation is “neuro”. class doctor { int doc_id; char dname[80]; char spl[80]; //type of specialisation float salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } char *rt_name() { return name; } void setsal(long p)
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 30 of 38
{ salary+=p; } void disp() { cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl; } };
Q23 Observe the program segment carefully and answer the question that follows: class item { int item_no; char item_name[20]; public: void enterDetail( ); void showDetail( ); int getItem_no( ){ return item_no;} }; void modify(item x, int y ) { fstream File; File.open( “item.dat”, ios::binary | ios::in | ios::out) ; item i; int recordsRead = 0, found = 0; while(!found && File.read((char*) &i , sizeof (i))) { recordsRead++; if(i . getItem_no( ) = = y ) { _________________________//Missing statement File.write((char*) &x , sizeof (x)); found = 1; } } if(! found) cout<<”Record for modification does not exist” ; File.close() ; } If the function modify( ) is supposed to modify a record in the file “ item.dat “, which item_no is y, with the values of item x passed as argument, write the appropriate statement for the missing statement using seekp( ) or seekg( ), whichever is needed, in the above code that would write the modified record at its proper place.
Q24 Observe the program segment carefully and answer the question that follows: class item
{ int item_no;
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 31 of 38
char item_name[20]; public: void enterDetails( ); void showDetail( ); int getItem_no( ){ return item_no;} }; void modify(item x ) {fstream File; File.open( “item.dat”, _______________ ) ; //parameter missing item i; while(File .read((char*) & i , sizeof (i))) {if(x . getItem_no( ) = = i . getItem_no( )) {File.seekp(File.tellg( ) – sizeof(i)); File.write((char*) &x , sizeof (x)); } else File.write((char*) &i , sizeof (i)); } File.close() ; }
If the function modify( ) modifies a record in the file “ item.dat “ with the values of item x passed as argument, write the appropriate parameter for the missing parameter in the above code, so as to modify record at its proper place.
Q25 Observe the program segment given below carefully and fill the blanks marked as Line 1 and Line 2 using fstream functions for performing the required task. #include<fstream.h> class Stock { long Ino; // Item Number char Item[20]; // Item Name int Qty; // Quantity public: void Get(int); Get(int);// Function to enter the content void Show( ); // Function to display the content void Purchase(int Tqty) { Qty+ = Tqty; // Function to increment in Qty } long KnowIno( ) { return Ino; } };
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 32 of 38
void Purchaseitem(long PINo, int PQty) // PINo -> Info of the item purchased // PQty -> Number of items purchased { fstream file; File.open(“ITEMS.DAT”,ios::binary|ios::in|ios::cut); int Pos=-1; Stock S; while (Pos== -1 && File.read((char*)&S, sizeof(S))) if (S.KnowInc( ) == PINo) { S.Purchase(PQty); // To update the number of items Pos = File.tellg()- sizeof(S); //Line 1 : To place the file pointer to the required position ______________________________________; //Line 2 : To write the objects on the binary file ______________________________________; } if (Pos == -1) cout<<“No updation done as required Ino not found...”; File.close( ); }
Q26 Observe the program segment given below carefully and fill the blanks marked as Statement 1 and Statement 2 using seekg( ), seekp( ), tellp( ) and tellg() functions for performing the required task. # include <fstream.h> class PRODUCT { int Pno; char pname [20]; int qty; public : void ModifyQty();// The function is to modify quantity of a PRODUCT }; void PRODUCT :: ModifyQty ( ) { fstream Fil; Fil.open(“PRODUCT.DAT”,ios::binary | ios::in | ios::out); int MPno; cout<<“Product No to modify quantity :”; cin>>MPno; while( Fil.read ((char*) this, sizeof (PRODUCT))) { if (MPno ==Pno) {
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 33 of 38
cout<<“present quantity:” <<Qty<<endl; cout<<“changed quantity:”; cin>>Qty; int position = ________; //Statement 1 ___________________; //Statement 2 Fil.write ((char*) this, sizeof (PRODUCT)); // Re-writing the Record } } Fil.close( );}
Q27 Observe the program segment given below carefully and fill the blanks marked as Statement 1 and Statement 2 using seekg() and tellg() functions for performing the required task. #include <fstream.h> class Employee { int Eno; char Ename[20]; public: //Function to count the total number of records int Countrec(); }; int Item::Countrec() { fstream File; File.open(“EMP.DAT”,ios::binary|ios::in); ______________________ //Statement 1 int Bytes = ______________________ //Statement 2 int Count = Bytes; sizeof(Item); File.close(); return Count; }
Q28 Write a function in C++ to count the no. of “Me” or “My” words present in a text file “DIARY.TXT”. If the file “DIARY.TXT” content is as follows : My first book was Me and My family. It gave me chance to be known to the world. The output of the function should be Count of Me/ My in file :3
Q29 Assuming the class EMPLOYEE given below, write functions in C++ to perform following: (i) Write the objects of EMPLOYEE to a binary file. (ii) Read the objects of EMPLOYEE from binary file and display them on screen. class EMPLOYEE { int ENO; char ENAME[10]; public :
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 34 of 38
void GETIT() { cin >> ENO; gets (ENAME); } void SHOWIT() { cout <<ENO << ENAME ; cout<<endl; } };
Q30 Consider the class declaration: class BUS { int bus_no; char destination[20]; float distance; public : void Read(); // To read an object from the keyboard void Write (); // To write an object into a file void Show (); // To display the file contents on The monitor }; Complete the member functions definitions.
Q31 Write a function in C++ to search for a laptop from a binary file “LAPTOP.DAT” containing the objects of class LAPTOP (as defined below). The user should enter the Model No and the function should search and display the details of the laptop. class LAPTOP { long ModelNo; float RAM, HDD; char Details[120]; public: void StockEnter ( ) { cin>>Model>>No>>RAM>>HDD; gets(Details); } void StockDisplay( ) {cout<<ModelNo<<RAM<<HDD<<Details<<endl; } long ReturnModelNo ( ) { return ModelNo ; } };
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 35 of 38
Q32 Write a function in C++ to search and display the details of all flights, whose destination is “Mumbai” from “FLIGHT.DAT”. Assuming the binary file is containing objects of class FLIGHT. class FLIGHT { int Fno; //Flight Number char From[20] ; //Flight Starting point char To[20] ; //Flight Destination public : char* GetFrom( ) { return From ; } char* GetTo( ) { return To ; } void Enter( ) { cin >> Fno ; gets (From) ; gets(To) ; } void Display( ) { cout << Fno<< “:” << From << “:” << To << endl ; } };
Q33 A binary file “Students.dat” contains data of 10 students where each student’s data is an object of the following class:
class Student { int Rno;char Name[20]; public: void EnterData() {cin>>Rno; cin.getline(Name,20); void ShowData() {cout<<Rno<<” - ”<<Name<<endl;} };
With reference to this information, write output of the following program segment: ifstream File; Student S; File.open(“STUDENTS.DAT”,ios::binary|ios::in); File.seekg(0, ios::end);
cout<<File.tellg();
Q34 Assuming the class Account given below and a binary file BANK.DAT contains objects of this class, write functions in C++ to perform the followings:
(i) Deposit ( ), which deposits amount x to account number y. (ii) Withdraw ( ), which withdraws amount x from account number y.
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 36 of 38
class Account{ int acc_no; char name[20]; float balance; public: float getBalance( ) { return balance; } void setBalance(float f ) { balance = f; } int get_acc_no( ) { return acc_no; } };
Multiple choice based
Q1 What enables a program to store the data permanently on secondary storage devices? (a) monitor (b) printer (c) file (d ) None of these
Q2 A collection of related data stored on some storage devices such as a hard disk, magnetic tape or floppy disk. (a) program (b) process (c) file (d ) None of these
Q3 Data files can be classified as (a) Text File (b) Binary File (c) Both (a) & (b) (d ) None of these
Q4 The files that store data in the form of machine form are known as (a) Text File (b) Binary File (c) Both (a) & (b) (d ) None of these
Q5 The files that store data as strings of characters are known as (a) Text File (b) Binary File (c) Both (a) & (b) (d ) None of these
Q6 A flow of data in the form of a sequence of bytes is known as____ (a) word (b) string (c) stream (d ) None of these
Q7 The stream that reads the data from the device and supplies it to the program is known as (a) input stream (b) output stream (c) Both (a) & (b) (d ) None of these
Q8 The stream that receives data from the program and writes it to the device is known as
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 37 of 38
(a) input stream (b) output stream (c) Both (a) & (b) (d ) None of these
Q9 Which one is file input stream class ? (a) ifstream (b) ofstream (c) both (a) & (b) (d ) None of these
Q10 Which one is file output stream class (a) ifstream (b) ofstream (c) both (a) & (b) (d ) None of these
Q11 Which is both file input and output stream class (a) ifstream (b) ofstream (c) fstream (d ) None of these
Q12 A file can be opened by (a) constructor (b) open( ) (c) both (a) & (b) (d ) None of these
Q13 Two or more file modes can be combined using the operator (a) bitwise OR (|) (b) bitwise AND ( &) (c) both (a) & (b) (d ) None of these
Q14 The default mode for the ifstream class is (a) ios::in (b) ios::out (c) both (a) & (b) (d ) None of these
Q15 The default mode for the ifstream class is (a) ios::in (b) ios::out (c) both (a) & (b) (d ) None of these
Q16 By default all files are open in which mode (a) text mode (b) binary (c) both (a) & (b) (d ) None of these
Q17 The open in which mode is compulsory to close the file by close( ) method (a) constructor (b) open( ) (c) both (a) & (b) (d ) None of these
Q18 Which method is used to read the data from a file (a) get( ) (b) read( ) (c) both (a) & (b) (d ) None of these
Q19 Which method is used to write the data to the file (a) put( ) (b) write( ) (c) both (a) & (b) (d ) None of these
Q20 The current position of a get pointer can be known by using (a) tellg( ) (b) tellp( ) (c) seekg( ) (d ) seekp( )
Q21 The current position of a put pointer can be known by using (a) tellg( ) (b) tellp( ) (c) seekg( ) (d ) seekp( )
Q22 Which of these stream classes can be used to read data from a file? (a) fstream (b) ifstream ( c) ofstream (d ) both (a) & (b)
Q23 Which of these file modes allows to write data anywhere in a file? (a) ios::ate (b) ios::app
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 38 of 38
(c) ios::out (d ) ios::trunc
Q24 Which of these functions allows to change the position of the get pointer? (a) tellg( ) (b) tellp( ) (c) seekg( ) (d ) seekp( )
Q25 Which of these refers to the end position of a file? (a) ios::beg (b) ios::end (c) ios::cur (d ) None of these
Q26 Which of these functions returns a non-zero value if end of file is encountered while reading data from a file ? (a) eof( ) (b) fail( ) (c) bad( ) (d ) good( )