Table of Contents
NCERT Solutions for Class 12 Computer Science (C++) – Data File Handling
TOPIC-1
Data File Handling :
Short Answer Type Questions-I[2 marks each]
Question 1.
Write a user defined function word_count() in C+ + to count how many words are present in a text file named “opinion.txt”. For Example, if the file opinion.txt contains following text:
Co-education system is necessary for a balanced society. With co-education system. Girls and Boys may develop a feeling of mutual respect towards each other.
The function should display the following :
Total number of words present in the text file are:24
Answer:
void word_count () { ifstream i;char ch[20];int c=0; i.open("opinion.txt"); while(!i.eof()) { i>>ch; C=C+1; } cout<<"Total number of words present in the text file are: "<<c; }
Question 2.
Write a function in C + + to count and display the no of three letter words in the file “VOWEL.TXT”.
Example :
If the file contains :
A boy is playing there. I love to eat pizza. A plane is in the sky.
Then the output should be : 4
Answer:
#include #include void wordcount() { char word[80]; int cnt=0; ifstream fl; f1.open("VOWEL.TXT"); while (fl>>word) { if (strlen(word) == 3) { cnt++; cout<<word<<endl; } } cout<<" number of three letter words = ”<<cnt; f1.close(); }
Question 3.
Write a function AECount() in C++, which should read each character of a text file NOTES. TXT, should count and display the occurrence of alphabets A and E (including small cases a and e too).
Example :
If the file content is as follow :
CBSE enhanced its CCE guidelines further.
The AECount() function should display the output as
A:1
E:7
Answer:
Void AECount () { Fstream obj; Obj.open ("NOTES.TXT", ios :: in) ; char x; int i=o, Sum A=0, Sum E=0, while (obj.get (ch)!=0) { obj . get (x) ; if (x=="A"||? x=="a") SumA =SumA+l; if(x=="E"|| x =="e") SumE=sumE+l; } cout<<"A:"<<sumA<<endl; Cout<<"E:"<< SumE; }
Question 4.
Write a function Countaroma() to count and display the number of times “Aroma” occurs in a text file “Cook.txt”.
Note : Only complete word “Aroma” should be counted. Words like “Aromatic” should not be counted.
Answer:
Void Countword () { fstream tfile; clrscr(); tfile.open ("Cook.txt", ios::in); char arr[80]; char ch; int i=0;sum=0;n=0; while(tfile) { tfile.get (ch) arr[i] = ch; i++ ; if (strcpy(ch, "Aroma")) { i--; sum = sum+i; n++; } } Cout<<"Total number of Aroma:" <<n; }
Question 5.
Write a function EUCount ( ) in C++, which should read each character of a text file IMP TXT, should count and display the occurrence of alphabets E and U (including small cases e and u too).
Example:
If the file content is as follows ;
Updated information is simplified by official websites.
The EUCount() function should display the
output as
E:4
U:1
Answer:
void EUCount () { fstream obj; obj. open("IMP.TXT"); char ch; int i = 0 , sumE=0, sumU=0 ; while (obj. get (ch)! =0) {obj. get (ch); if(ch=="E"||ch=="e") SumE=sumE+l; if(ch=="U" ??ch =="u") SumU=SumU+l; } cout << "E : " «sum E<<endl; cout<<"U:"<<sumU<<endl; }
Question 6.
Write a function CountDig() in C++ which reads the content of a text file story.txt and displays the number of digits in it
For example if the file contains:
Amrapali was a queen of Gareware Kingdom in the year 1911. She had 2 daughters.
Her palace had 200 rooms.
Then the output on the screen should be :
Number of digits in Story: 8
Answer:
void CountDig () { ifstream fin ("STORY.TXT"); char ch; int count=0; while(!fin.eof ()) {fin>>ch; if(isdigit(ch)) count++; } cout<<"Number of digit in Story: "<<count; fin:close(); }
Question 7.
Write a function in C + + to count the number of lines starting with a digit in a text file “Diary.Txt”.
Answer:
int countNum () { ifstream fin("Diary.Txt"); char ch[80]; int count = 0; while (!fin.eof()) { fin.getline (ch, 80); if (isdigit (ch[0]) count ++; } fin.close( ); return count; }
Question 8.
Write a function in C+ + to read the content of a text file “DELHI.TXT” and display all those lines on the screen, which are either starting with ‘D’ or starting with ‘M’.
Answer:
void disp () { ifstream FILE("DELHI.TXT"); int CA= 0; char LINE [80]; while(FILE.getline(LINE,80)) if(LINE [0]=='D' | | LINE[0]= 'M') puts(LINE); FILE.close(); }
Question 9.
Write a function in C++ to read the content of a text file “PLACES.TXT” and display all those lines on screen, which are either starting with ‘P’ or starting with ‘S’.
Answer:
void disp () { ifstream FILE("PLACES.TXT"); int CA=0; char LINE [80]; while(FILE.getline(LINE,80)) if(LINE[0]=='P' | | LINE[0]=='S') puts(LINE); FILE.close(); }
Question 10.
Write a function CountYouMe ( ) in C+ + which reads the contents of a text file story.txt and counts the words You and Me (not case sensitive).
For example, if the file contains:
You are my best friend.
You and me make a good team.
The function should display the output as:
Count for you : 2
Count for Me : 1
Answer:
void countyoume ( ) { ifstream fil("story.txt"); char word [80]; int WC = 0, WM = 0; while (! fil.eof()) { fil>>word; if ((strcmp WC++ ; (word, "You") = = 0) if (strcmp (word, "Me") = = 0) ) WM++ ; } cout <<"count for you" << WC; cout <<"count for me" << WM; fil. close ( ) ;}
Question 11.
Write a function in C + + to count the number of lines present in a text file “STORY.TXT”.
Answer:
void CountLine () { ifstream FIL("STORY.TXT"); int LINES=0; char STR[80]; while {FIL.getline(STR, 80); LINES++;} cout<<"No. of Lines:"<<LINES; f.close(); }
TOPIC-2
Data File Handling : binary file
Very Short Answer Type Questions[1 mark each]
Question 1.
Write the command to place the file pointer at the 10th and 4th record starting position using seekp() or seekg() command. File object is “file”? and record name is “STUDENT”.
Answer:
file.seekp( 9 * sizeof(STUDENT), ios::beg);
file.seekp( 3 * sizeof(STUDENT), ios::beg);
Question 2.
Find the output of the following C++ code considering that the binary file sp.dat already exists on the hard disk with 2 records in it.
class sports { int id; char sname[20]; char coach[20]; public: void entry(); void show(); void writing(); void reading(); }s; void sports::reading() { ifstream i; i.open("sp.dat"); while(1) { i.read((char*)&s.size of (s)); if(i.eof()) break; else cout<<"\n"<<i.tellg(); } i.close () ; } void main() { s.reading(); }
Answer:
42
84
Question 3.
A binary file “games.dat” contains data of 10 games where each game’s data is an object of the following class :
class game { int gameno; char game_name[20]; public : void enterdetails(){cin>>gameno; gets(game_name);} void enterdetails() {cout<<gameno<<endl<< game_name;} }; With reference to this information, write C++ statement in the blank given below to move the file pointer to the end of file, ifstream ifile; game G; ifile.open("games.dat",ios::binary| ios::in); cout<<ifile.tellg();
Answer:
ifile.seekg(0,ios::end);
Question 4.
Fill in the blanks marked as Statement 1 and Statement 2, in the program segment given below with appropriate functions for the required task,
class Agency { int ANo; //Agent Code char AName [20]; //Agent Name char Mobile [12]; //Agent Mobile public: void Enter (); /*Function to enter details of agent*/ void Disp (); /‘Function to display details of agent*/ int RAno () {return ANo; } void UpdateMobile() /‘Function to update Mobile*/ { cout<<"Updated Mobile:"; gets(Mobile); }; void AgentUpdate () { fstream F; F. open ("AGENT.DAT", ios:: binary |ios:: in | ios:: out); int Updt=0; int UAno; cout<<"Ano (Agent No - to update Mobile):"; cin>> UAno; Agency A; while (!Updt && F.read ((char*) &A, sizeof (A))) { if (A. RAno ()==UAno) { //Statement 1: To call the function to Update Mobile No.
//Statement 2: To reposition file pointer to re-write the updated object back in the file F. Write ((char*)&A, sizeof (A)); Updt++;
} } if (Updt) cout<<"Mobile Updated for Agent" <<UAno<<endl; else cout<< "Agent not in the Agency"<<endl; F. close (); }
Answer:
Statement 1:
A. Update Mobile ();
Statement 2:
F. seekg (-l*size of (A),ios:: (cur);
Question 5.
Fill in the blanks marked as Statement 1 and Statements 2, in the program segment given below with appropriate functions for the required task.
class Medical { int RNo; //Representative Code char Name [20]; //Representative Name char Mobile [12]; //Representative Mobile public : void Input (); // Function to enter all details void Show (); //Function to display all details int RRno () {return RNo;} void Change Mobile () //Function to change Mobile { cout<<"Changed Mobile:"; gets (mobile); } }; void RepUpdate () { fstream F; F. open ("REP. DAT", ios : : binaryl ios:: in| ios:: out): int Change=0; int URno; cout<<"Rno (Rep No-to update Mobile) :"; cin>>URno; Medical M; while (! Change && F.read((char*) &M, sizeof (M)) { if (M. RRno()==URno) { //Statement 1: To call the function to change Mobile No. //Statement 2: To reposition file pointer to re-write //the updated object back in the file ; F. write ((char*) &M, Sizeof (M)) ; Change++; } } if (change) cout <<"Mobile Changed for Rep" <<URno<<endl; else cout <<"Rep not in the Medical"< F. close (); }
Answer:
Statement 1:
M. Change Mobile ();
Statement 2:
F. seekp (-1* sizeof (M), ios :: (ur);
Question 6.
Fill in the blanks marked as Statement 1 and Statement 2, in the program segment given below with appropriate functions for the required task.
class Agent { long ACode; //Agent Code char AName [2 0] ; //Agent Name int Commission; public: void Enter (); //Function to enter details of Agent void Display (); //Function to display details of Agent void Update (int c) //Function to modify commission { Commission = C; } int GetComm(){return Commission;} long GetAcodeO {return Acode;} }; void ChangeCommission (long AC, int CM) //AC " Agent Code, whose commission needs to change //CM " New Commission { fstream F; F. open ("AGENT.DAT", ios : : binary |ios : : in|ios : : out); char Changed='N'; Agent A; while (Changed=='N'&& F. read ((char*) &A, size of (A))) { if (A. GetAcode ()==AC) { Changed = 'Y'; A. Update (CM); //Statement 1: To place file pointer to the required position ------------------------; //Statement 2: To write the object A on to the binary file -------------------------; } } if (Changed=='N') cout <<"Agent not registered."; F. close ();
Answer:
Statement 1:
F. seekg (position);
Statement 2:
F. write ((char *) & A, size of (A));
Question 7.
Fill in the blanks marked as Statement 1 and Statement 2, in the program segment given below with appropriate functions for the required task.
class Customer { long int CNo; //Customer Number char CName[20]; //Customer Name char Email[30]; //Email of Customer public : void Allocate(); //Function to allocate a member void Show(); //Function to show customer data void ModifyEmail() //Function to modify Email , { cout<<"Enter Modified Email:"; gets(Email); } long int GetCno( ) {return CNo;} }; void ChangeData( ) { fstream File; File.open ("CUST.DAT", ios: :.binary | ios: :in|ios: :out); int Change=0, Location; long int ChangeCno; cout<<"Cno - whose email required to be modified:"; cin>>ChangeCno; Customer CU; while(Modify && File,read((char*)&CU, sizeof(CU))) { if (CU.GetCno()==ChangeCno) { CU.ModifyEmail (); Location=File.tellg()- sizeof(CU); //Statement 1: To place file pointer to the required position //Statement 2: To write the object CU on to the binary file Change ++; } } if (Change) cout<<"Email Modified... "<<endl; else cout <<"Customer not found... "<<endl; File. close(); }
Answer:
Statement 1:
File.seekp (-l*size of (CU), ios ::cur);
Statement 2:
File.write ((char*)&CU, sizeof (CU));
Question 8.
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 EnterDataO {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();
Answer:
A1
B2
C3
Question 9.
Observe the program segment given below carefully and answer the questions that follow:
class Stock { int Ino,Qty; char Item[20]; public: void Enter( ){cin>>Ino; gets(Item); cin>>Qty;} void Issue (int Q) {Qty+=Q;} void Purchase (int Q) {Qty- =Q;) int GetlnoO {return Ino;} } ; void Purchaseltem (int Pino, int PQty) { fstream File; File.open ("STOCK.DAT", ios:: binary |ios: : in|ios : : out); Stock S; int Success=0; while (Success==0 && File . read ((char*) &S, sizeof (S))) { if (Pino==S. Getlno ()) { S. Purchase (PQty); //Statement 1 //Statement 2 Success++ ; } } if (Success==l) cout<<" Purchase Updated" <<endl; else cout<<"Wrong Item No"<<endl; File . close ( ) ; }
(i)Write statement 1 to position the file pointer to the appropriate place, so that the data updation is done for the, required item.
(ii)Write statement 2 to perform the write operation so that the updation is done in the binary file.
Answer:
(i) file.seekp(-sizeof(Qty), ios::cur);
(ii) file.write((char*)&S, sizeof (stock));
Question 10.
Observe the program segment given below carefully and answer the questions that follow:
class Inventory { int Ano, Qty; char Article [20]; public: void Input () (cin>>Ano; gets(Article); cin>>Qty;} void Issue (int Q) {Qty+=Q;} void Procure (int Q) {Qty-=Q;} int GetAno () {return Ano;} }; void ProcureArticle (int TAno, int TQty) { fstream File; File.open("STOCK.DAT", ios :: binary|ios :: in|ios :: out); Inventory I; int Found=0; while (Found==0 && File, read((char*)&I. sizeof(I))) if (TAno=|S.GetAno()) { I. Procure (TQty); //Statement 1 //Statement 2 Found++; } } if (Found==l) { cout<<" Procurement Updated" << endl ; else cout<<"Wrong Article No"<<endl; File.close ( ) ;}
(i) Write statement 1 to position the file pointer to the appropriate place, so that the data updation is done for the required term.
(ii) Write statement 2 to perform the write operation so that the updation is done in the binary file.
Answer:
(i) file.seekp(sizeof (qty), ios :: cur);
(ii) file.write((char*)& |, sizeof(|));
Short Answer Type Questions-I[2 marks each]
Question 1.
Consider a file F containing objects E of class Emp. [Delhi, 2015]
(i) Write statement to position the file pointer to the end of the file.
(ii) Write statement to return the number of bytes from the begining of the file to the current position of the file pointer.
Answer:
(i) F. seekg (0,ios::end);
(ii) F.tellg();
Question 2.
Write a function RevText() to read a text file “Input.txt” and Print only word starting with ‘I’in reverse order. [Delhi, 2015]
Example : If value in text file is : INDIA IS MY COUNTRY v
Output will be : AIDNI SI MY COUNTRY
Answer:
void RevText () {ifstream in ("Input.txt"); char word[25]; while(in) { in >>word; if (word[0] = = 'I' ) cout<<strrev(word); else cout<<word; }
Question 3.
Write a function in C++ to search display details, where destination is “Chandigarh” from binary file “Flight.Dat”. Assuming the binary file is containing the objects of the following class :
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 input() {cin>>Fno>>; gets(From); get (To);} void show() {cout<<Fno<<":"<<From<<":"<<To<<endl; } };
Answer:
void Dispdetails () {ifstream fin ("Flight.Dat"); Flight F; while (fin) {fin.read((char*)&F,sizeof(F)) if (strcmp(F.GetTo0, "Chandigarh")) F.show(); } }
Question 4.
Write function definition for TOWER () in C++ to read content of a text file WRITEUE TXT. Count the presence of word TOWER and display the number of occurrences of this word.
Note:
— The word TOWER should be an independent word
— Ignore type cases (i.e. lower/upper case) Example:
If the content of the file WRITEUETXT is as follows:
Tower of hanoi is an interesting problem. Mobile phone tower is away from here. Views from EIFFEL TOWER are amazing.
The function TOWER() should display the following:
3
Answer:
void TOWER ()
{
int count = 0;
ifstream f (“WRITEUP.TXT”);
char s [20];
while (! f . eof () )
{
f >>S;
if (strcmpi (s, “TOWER”) = =0)
count ++;
}
cout<<count; f.close () ;
}
OR
Any other correct function defintion
Question 5.
Write a definition for function COSTLY() In C++ to read each record of a binary file GIFTS. DAT, find and display those items, which are priced more than 2000. Assume that the file GIFTS.DAT is created with the help of objects of class GIFTS, which is defined below:
class GIFTS { int CODE; char ITEM [20] ; float PRICE; public : void procure () { cin>>CODE; gets (ITEM); cin>>PRICE; } void View () { cout<<CODE<<":"<<ITEM<<":"< } float GetPrice () {return PRICE; }.
Answer:
void COSTLY () { GIFTS G; ifstream fin ("GIFTS.DAT" , ios : : binary); while (fin.read( (char *)&G, sizeof (G))) { if (G.GetPrlce () >2000) G.View (); } fin. close ();
OR
Any other correct equivalent function definition
Question 6.
Find the output of the following C++ code considering that the binary file MEMBER. DAT exists on the hard disk with records of 100 members:
class MEMBER { int Mno; char Name [20]; public : void In (); void out (); }; void main () { fstream MF; MF.open (:MEMBER.DAT", ios :: binary |ios :: in); MEMBER M; MF.read ((char*) &M, sizeof (M)) ; MF.read ((char*)) &M, sizeof (M)); MF.read ((char*) &M, sizeof (M)); int POSITION = MF. tellg () / sizeof (M) ; Cout<<"PRESENT REOCRD :"< MF.close () ; }
Answer:
PRESENT RECORD : 3
Question 7.
Write function definition for SUCCESS () in C + + to read the content of a text file STORY.TXT, count the presence of word STORY and display the number of occurrence of this word.
Note:
— The word STORY should be an independent word
— Ignore type cases (i.e. lower/upper case)
Example:
If the content of the file STORY.TXT is as follows
Success shows others that we can do it. It is possible to achieve success with hard work. Lot of money does not mean SUCCESS.
The function SUCCESS() should display the following:
3
Answer:
void SUCCESS () { int count = 0 ; ifstream f ("STORY.TXT") ; char s [20] ; while (! f. eof () ) { f >>S; if (strcmpi (s, "STORY") = = 0) //OR if (strcmpi (s, "SUCCESS")==0) count++; } cout<<count; f.close () ;
OR
Any other correct function definition
Question 8.
Write a definition for function Economic ( ) in C++ to read each record of a binary file ITEMS.DAT, find and display those items, which costs less than 2500. Assume that the file ITEMS. DAT is created with the help of objects of class ITEMS, which is defined below :
class ITEMS { int ID; char GIFT [20] ; float cost ; public : void Get () { cin>>CODE,-gets (GIFT) ; cin>>cost; } void See () { COUt < } float GetCost 0 {return Cost;}. } ;
Answer:
void Economic () { ITEMS I; ifstream fin (" ITEMS.DAT",ios:: binary); while (fin.read ((char *)&I,sizeof (I))) { if (I.GetCost ()<2500) I. See (); } fin. close (); }
OR
Any other correct equivalent function definition
Question 9.
Find the output of the following C++ code considering that the binary file CLIENTS. DAT exists on the hard disk with records of 100 members.
class CLIENTS { int Cno; char Name [20]; public : void In (); void out () ; } ; void main ( ) { fstream CF; CF.open "CLIENTS.DAT", ios :: binary | ios :: in); CLIENTS C ; CF.read ((char*) &C, sizeof (C)); CF.read ((char*) &C, sizeof (C)); CF.read ((char*) &C, sizeof (C)); int POS = CF. tellg ()/sizeof (C) ; cout < <"PRESENT RECORD :"< < POS < <endl; CF.close (); }
Answer:
PRESENT RECORD : 3
Question 10.
Write function definition for WORDABSTART () in C++ to read the content of a text file, JOY. TXT, and display all those words, which are starting with either ‘A’, ‘a’ or ‘B’, ‘b’.
Example:
If the content of the file JOY.TXT is as follows :
I love to eat apples and bananas. I was travelling to Ahmedabad to buy some clothes.
The function WORDABSTART() should display the following:
apples bananas Ahmedabad buy
Answer:
void WORDABSTART () { ifstream fil; fi1.open ("JOY.TXT"); char W[20]; fi1> >W; while(!fil.eof())//OR While(fil) { if(strlen(w)==4) cout<<W<<" "; fi1> >W; } fil.close ();//Ignore }
Question 11.
Write a definition for function OFFER() in C+ + to read each object of a binary file OFFER.DAT, find and display details of those ITEMS, which has status as “ON OFFER”. Assume that the file OFFER.DAT is created with the help of objects of class ITEMS, which is defined below:
class ITEMS { int ID;char Item[20];Status[20]; float Price; public: void GetonstockO { cin>>ID;gets(Item);gets(Status); cin>>Price; } void view() { cout<<ID<<":"<<Item<<":"< } char*IStatus(){return Status}. };
Answer:
void OFFER () { ITEMS; ifstream fin; fin.open("OFFER.DAT",ios::binary); while(fin.read(char*)&G size of(G)) { if strcmp (G.Get status(),"ON OFFER")==0) G.view(); } fin.close()///Ignore }
Short Answer Type Questions-II[3 marks each]
Question 1.
Given the binary file CAR.Dat, containing . records of the following class CAR type:
class CAR { int C_No; char C_Name[20]; float Mileage; public : void enter( ) { cin>> C_No ; gets(C_Name) ; cin >>Mileage; } void display( ) { cout<<C_No; cout<<C_Name; cout<<Mileage; } int RETURN_Mileage( ) { return Mileage; } };
Write a function in C++, that would read contents from the file CAR.DAT and display the details of car with mileage between 100 to 150.
Answer:
void CARSearch () { fstream FIL; FIL.open("CAR.DAT" , ios::binary|ios::in); CAR C; int Found = 0; while(FIL.read((char*)&C,sizeof(C))) { if ((C.RETURN_Mileage( )>100) && (C.RETURN_Mileage( ) < 150) ) { C.display(); Found++; } } if (Found==0) cout<<"Sorry! No car found with mileage between 100 to 150"; FIL.close () ; }
Question 2.
Given a binary file “SPORTS.DAT” containing records of the following class :
class Player { char PNO[10]; //player number char Name[20]; //Name of player int rank; //rank of the player public : void EnterData() { gets (PNO) ;gets (Name);cin>>rank; } void DisplayData() { cout<<setw(12)<<PNO; cout<<setw(32)<<Name; cout<<setw(3)<<rank<<endl; } int Ret_rank() {return rank;} } ;
Write a function in C++ that would read contents of the file “SPORTS.DAT” and display the
details of those jolayers whose rank is above 500.
Answer:
Void show() { fstream file; file.open( ("SPORTS. DAT"),ios::binary:ios::in)); player P; while (file.read((char*)&P,sizeof(P))) if(P.rank>500) { Pi P.DisplayData () ; P.close(); } }
Question 3.
Assuming the Class WORKER as declared below, write a function in C++ to read the objects of WORKER from binary file named WORKER. DAT and display those records of workers, whose Wage is less then 300.
class WORKER { int WNO; char WName [30] ; float Wage; public: void Enter() {cin>>WNo; gets (WName); cin>>wage;} void DISPO {Cout<<ENo<<'*'< float GetWage () {return Wage,-} };
Answer:
void Display() { ifstream fin; fin.open("WORKER.DAT",ios::in | ios:: binary) ; WORKER W; while (! fin. eof () ) { fin.read((char*)&W,sizeof(W) ) ; if W. GetWage() <300) W. DISP (); } fin. close (); }
Question 4.
Assuming the class TOYS as declared below, write a function in C++ to read the objects of TOYS from binary file TOYS. DAT and display those details of those TOYS, which are meant for children of AgeRange “5 to 8”.
class TOYS { int ToyCode; char ToyName[10]; char AgeRange; public: void Enter() { cin>>ToyCode; gets (ToyName); gets(AgeRange); } void Display() { cout<<ToyCode ToyName<<endl; cout<<AgeRange<<endl; } char*WhatAge() {returnAgeRange;} };
Answer:
void READTOYS() { fstream obj; obj.open ("TOYS.DAT",ios::binary); TOYS T; while (obj.read ((char*)&T, Sizeof(T))) if(T. WhatAge()>=5&&T.whatAge<=8) T. Display(); obj. Close(); }
Question 5.
Assuming the class GAMES as declared below, write a functions in C++ to read the objects of GAMES from binary file GAMES.DAT and display those details of those GAMES, which are meant for children of AgeRange “8 to 13”.
class GAMES { int GameCode; char GameName [10]; char AgeRange; public: void Enter() { cin>>GameCode; gets(GameName); gets (AgeRange); } void Display() { cout<<GameCode<<":"GameName<<endl; cout<<AgeRange<<ehdl; } char* AgeR() {return AgeRange}; };
Answer:
Void READGAMES () { fstream obj ;obj. open ("GAMES.DAT",ios::binary); Games T; while (obj. read ((char*)&T,size of(T) ) ) if (T. AgeR()>=8&& T. What Age <=13) T. Display (); obj. closet) }
Question 6.
Assuming the class ANTIQUE as declared below, write a function in C++ to read the objects of Antique from binary file ANTIQUE. DAT and display those antique items, which are priced between 10000 and 15000.
class ANTIQUE { int ANO; char Aname [10] ; float price; public : void BUY() {cin>>ANO;gets(Aname); cin>> price;} void SHOW ( ) { cout<<ANO<<endl; cout < cout<<Price<<endl; } float Get Price ( ) {return Price;} };
Answer:
void Disp( ) { ifstream fin; fin.open ("ANTIQUE.DAT", ios:: in |ios : : out | ios : : binary); Antique A; while (!fin.eof( )) { - fin.read ((char*) &A, sizeof(A)); if (A.GetPrice ( )> 10000 & A.GetPrice( )<15000) A.SHOW( ); } fin.close( ) ; }
Question 7.
Assuming the class VINTAGE as declared below, write a function in C++ to read the objects of VINTAGE from binary file VINTAGE.DAT and display those vintage vehicles, which are priced between 200000 and 250000.
class VINTAGE { int VNO; //Vehicle Number char VDesc[10]; //Vehicle Description float price; public: void GET( ) {cin>>VNO;gets(VDesc); cin>>Price;} void VIEW( ) { cout<<VNO<<endl; cout<<VDesc<<endl; cout<<Price<<endl; } float ReturnPrice ( ) {return Price;} };
Answer:
void Disp( ) { ifstream fin; fin.open ("VINTAGE.DAT", ios ::in| ios : : binary); vintage V; while (Ifin.eof()) { fin.read ((char*)&V, sizeof(V)); if (V.ReturnPrice( )> 200000 & &V.ReturnPrice( )<250000) V.VIEW ( ); } fin.close ( ); }
Question 8.
Write a function display () in C + + to display all the students who have got a distinction (scored percentage more than or equal to 75) from a binary file “stud.dat”, assuming the binary file is containing the objects of the following class:
class Student { int rno; char sname [20]; int percent public; int retpercent() { return percent; } void getdetails() { cin>>rno; gets(sname); cin>>percent; } void showdetails() { cout<<rno; puts(sname); cout<<percent; } };
Answer:
void display() { student s; ifstream i("stud.dat"); while(i.read(char*)&s,sizeof(s))) { if(s.retpercent()>=75) S.showdetails(); } i.close(); }
Question 9.
Write a function in C++ to search for the details (Phone no. and Calls) of those phones, which have more than 800 calls from a binary file “phones.dat”. Assuming that this binary file contains records/objects of class phone, which is defined below.
class Phone { char Phoneno[10]; int Calls; public: void Get() {gets (Phoneno); cin>>Calls;} void Billing!){cout<<Phoneno<<"#"< int GetCalls(){return Calls;} };
Answer:
void Search () { ifstream infile; infile, open ("phones.dat"); if(! infile) { cout<<"can't open the'file"; exit(); } while(! infile.eof()) } { infile, read (Char #) & P, size of (P); if (P. GetCalls()>800) P. Billing (); } infile.close (); }
Question 10.
Write a function in C++ to search for the details (Number and Calls) of those Mobile phones, which have more than 100 calls from a binary file “mobile.dat”. Assuming that this binary file contains records/objects of class Mobile, which is defined below:
class Mobile { char Number [10]; int Calls; public: void Enter () {gets (Number); cin>>Calls;} void Billing () {cout<<Number<<"#"< int GetCalls() {return Calls;} } ;
Answer:
void Search ( ) { Mobile m; ifstream f; f.open ("mobile.dat"); while (!f.eof()) { f.read ((char*)&m, sizeof (m)); if (m.GetCalls0>100) m.Billing (); } }
Question 11.
Write a function in C++ to search for a camera from a binary file “CAMERA.DAT” containing the objects of class CAMERA (as defined below). The user should enter the model no and the function should search and display the details of the camera,
class CAMERA { long ModelNo; float Megapixel; int Zoom; char Details[120]; public: void Enter(){cin>>ModelNo>>Megapixel >> Zoom; gets (Details);} void Display( ) {cout< <ModelNo< <MegaPixel<<Zoom< long GetModelNo(){return ModelNo;} };
Answer:
void cameraSearch () { fstreamFIL; FIL.openCCAMERA.DAT", ios::binary|ios :: in ); CAMERA B; long bn; int Found = 0; cout<<"Enter the Model Number"; cin >> bn; while (FIL.read((char*)&B, sizeof (B))) { if (FIL.GetModelNo() = = bn) { B.Display(); Found ++; }} if(Found = = 0) cout<<"Sorry ! Camera not found"<<endl; FIL.close( ); }
Long Answer Type Questions[4 marks each]
Question 1.
Write function definition for WORD4CHAR() in C++ to read the content of a text file FUN.TXT. and display all those words, which have four characters in it.
Example:
If the content of the file FUN.TXT is as follows :
When I was a small child, I used to play in the garden with my grand mom. Those days were amazingly funful and I remember all the moments of that time.
The function WORD4CHAR() should display the following:
When used play with days were that time.
Answer:
Void WORD4CHAR () { ifstream f("FUN.TXT"); char ch[20] ; while (!f.eof()) { f >>ch; if(strlen(ch)==4) cout<<ch, } f close(), }
Question 2.
Write a definition for function ONOFFER()in C++ to read each object of a binary file TOYS. DAT, find and display details of those toys, which have status as “ON OFFER”. Assume that the file Toys.DAT is created with the help of objects of class TOYS, which is defined below:
Class TOYS { int TID; char Toy[20], Status[20]; float MRP; Public: void Getinstock() { cin>>TID;gets (Toy) ; gets (Status) ; cin»MRP:} void View() { Cout<<TID<<":"<<Toy<<":"<<MRP<< "":"<<Status<<endl; } Char *SeeOffer() {Return Status;} } ;
Answer:
Void ONOFFER () { TOYS T; Ifstream fin; fin.open("TOYS.DAT", ios ::binary) ; while(fin.read((char*)&T,size (T) )) { if (strcmp(T.see offer(),"ON OFFER")= = 0) T.view(); } fin.close();//Ignore }
Question 3.
Find the output of the following C++ code considering that the binary file CLIENT.DAT exists on the hard disk with a data of 1000 clients :
Class CLIENT { int Ccode;char CName[20]; public: void Register();void Display(); }; void main() { fstream CFile; CFile.Open ( "CLIENT. DAT",ios::binary|ios::in); CLIENT C; CFile. read ( (char*) & C , sizeof(C)) ; cout<< "Rec: "<<CFile.tellg()/ sizeof(C)<<endl; CFile. read ( (char*) & C , sizeof*(C)); CFile . read ( (char*) & C , sizeof(C)); cout<<"Rec:"<<CFile.tellg()/ sizeof(C)<<endl; CFile.close () ; }
Answer:
Rec: 1
Rec: 3
Discover more from EduGrown School
Subscribe to get the latest posts sent to your email.