Chapter 6: Data File Handling Class 12 Computer Science NCERT Solutions
Chapter 6 delves into the important concept of Data File Handling in C++. It introduces students to the various methods used to store and retrieve data from files, allowing programs to persist data beyond the program\’s execution. This chapter covers the essential file operations, including reading from and writing to files, file modes, and error handling during file operations. Mastery of file handling allows students to create programs that interact with external data, enabling more complex, real-world software solutions.
What You Will Learn in Chapter 6
In this chapter, students will learn the techniques for performing file input/output (I/O) operations in C++. This includes working with text files, binary files, file streams, and common functions associated with file handling in C++. Students will also understand how to open, close, read, and write data to files efficiently.
Key Topics Covered
Introduction to File Handling in C++
Definition: File handling enables the reading and writing of data to and from external files.
The need for file handling in real-world applications (e.g., databases, text files, log files).
Overview of file types: Text files (human-readable) vs Binary files (machine-readable).
File Streams in C++
File stream classes:
ifstream
(input file stream),ofstream
(output file stream),fstream
(input/output file stream).Syntax for creating file streams:
ifstream infile(\"file.txt\");
ofstream outfile(\"file.txt\");
fstream file(\"file.txt\", ios::in | ios::out);
Methods for opening and closing files:
open()
,close()
.
Opening and Closing Files
Different file modes:
ios::in
,ios::out
,ios::app
,ios::binary
, etc.Example:
ofstream file(\"data.txt\", ios::app);
Closing files using
close()
.Error handling during file opening (checking if the file opened successfully).
Reading and Writing Data to Files
Writing to files using
<<
(forofstream
) andwrite()
(for binary files).Reading from files using
>>
(forifstream
) andread()
(for binary files).Example: Writing and reading integers, strings, and formatted data.
Using manipulators (e.g.,
setw
,setprecision
) for formatting output.
Text File Operations
How to read and write text data:
Writing strings and numbers to text files.
Reading text data line-by-line using
getline()
.Handling end-of-file (EOF) using
eof()
.
Example: Storing and retrieving student records (name, roll number, marks) from a text file.
Binary File Handling
Difference between text and binary file formats.
Writing and reading binary data using
write()
andread()
.Benefits of binary files for efficiency and compactness.
Example: Storing complex data structures (e.g., objects, arrays) in binary format.
File Error Handling
Common file handling errors: file not found, permission denied, incorrect format.
Using
fail()
,eof()
,good()
, andbad()
to check file stream states.Example: Checking for errors after attempting to open a file.
Random Access Files
Introduction to random access in files.
Seeking and changing positions within files using
seekg()
andseekp()
.Writing and reading data from a specific position in the file.
Example: Using random access for updating records in a file.
File Pointers and File Operations
Using
tellg()
andtellp()
to get the current position in input/output files.Example: Displaying current file position and using it for file navigation.
Download Chapter 6 Solutions PDF – Data File Handling
Our downloadable PDF includes:
NCERT textbook solutions for all in-text questions and exercises.
Example code snippets and output predictions.
File handling syntax explanations and common mistakes.
Practice exercises for file I/O operations (text and binary files).
Step-by-step guides on handling file errors and working with file pointers.
Highlights of Our NCERT Solutions
Clear and concise explanations of file handling concepts with real code examples.
Detailed code samples for reading and writing both text and binary files.
Practical error-handling techniques and troubleshooting tips.
Visual aids and charts for understanding file modes and file pointer operations.
Comparisons between text and binary file formats for efficient data storage.
Recommended Preparation Tips
Practice writing programs to read and write simple text files before moving to binary files.
Familiarize yourself with various file modes (
ios::in
,ios::out
,ios::app
).Debug file handling errors, such as incorrect file opening and end-of-file issues.
Experiment with both text and binary file operations for a hands-on understanding.
Understand file error handling methods to ensure robust programs.
Additional Study Resources
Flashcards: File stream classes, modes, and error-handling methods.
Practice worksheets: Debugging file operations, completing programs with missing file operations.
Example programs: Storing and retrieving various data types using file handling.
Sample questions: Solving problems on text and binary file handling from previous exams.
Interactive quizzes: Testing knowledge of file stream operations and file modes.
Mastering Chapter 6 – Data File Handling
Mastering file handling is essential for building programs that manage persistent data, such as database systems, data logging systems, and text processing applications. Understanding file operations enhances your ability to develop real-world applications that require external data storage and retrieval.
With consistent practice and a solid grasp of file handling, students are well-prepared to move on to more complex topics like class-based file handling and data storage techniques in advanced programming courses.
Class 12 Computer Science (C++) – Chapter 6 Data File Handling
Short Answer Type Questions-I[2 marks each]
1. Word Count in File
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 << endl;
}
2. Count Three-Letter Words in File
#include <fstream>
#include <cstring>
void wordcount()
{
char word[80];
int cnt = 0;
ifstream fl;
fl.open("VOWEL.TXT");
while (fl >> word)
{
if (strlen(word) == 3)
{
cnt++;
cout << word << endl;
}
}
cout << "Number of three-letter words = " << cnt << endl;
fl.close();
}
3. Count Occurrences of A and E in File
void AECount()
{
fstream obj;
obj.open("NOTES.TXT", ios::in);
char x;
int sumA = 0, sumE = 0;
while (obj.get(x))
{
if (x == 'A' || x == 'a')
sumA++;
if (x == 'E' || x == 'e')
sumE++;
}
cout << "A: " << sumA << endl;
cout << "E: " << sumE << endl;
}
4. Count Occurrences of “Aroma” in File
void Countword()
{
fstream tfile;
tfile.open("Cook.txt", ios::in);
char arr[80];
int n = 0;
while (tfile >> arr)
{
if (strcmp(arr, "Aroma") == 0)
n++;
}
cout << "Total number of Aroma: " << n << endl;
}
5. Count Occurrences of E and U in File
void EUCount()
{
fstream obj;
obj.open("IMP.TXT");
char ch;
int sumE = 0, sumU = 0;
while (obj.get(ch))
{
if (ch == 'E' || ch == 'e')
sumE++;
if (ch == 'U' || ch == 'u')
sumU++;
}
cout << "E: " << sumE << endl;
cout << "U: " << sumU << endl;
}
6. Count Digits in File
void CountDig()
{
ifstream fin("STORY.TXT");
char ch;
int count = 0;
while (!fin.eof())
{
fin >> ch;
if (isdigit(ch))
count++;
}
cout << "Number of digits in Story: " << count << endl;
fin.close();
}
7. Count Lines Starting with a Digit
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;
}
8. Display Lines Starting with D or M
void disp()
{
ifstream file("DELHI.TXT");
char line[80];
while (file.getline(line, 80))
{
if (line[0] == 'D' || line[0] == 'M')
puts(line);
}
file.close();
}
9. Display Lines Starting with P or S
void disp()
{
ifstream file("PLACES.TXT");
char line[80];
while (file.getline(line, 80))
{
if (line[0] == 'P' || line[0] == 'S')
puts(line);
}
file.close();
}
10. Count “You” and “Me” in File
void countYouMe()
{
ifstream fil("story.txt");
char word[80];
int WC = 0, WM = 0;
while (!fil.eof())
{
fil >> word;
if (strcmp(word, "You") == 0)
WC++;
if (strcmp(word, "Me") == 0)
WM++;
}
cout << "Count for You: " << WC << endl;
cout << "Count for Me: " << WM << endl;
fil.close();
}
11. Count Lines in File
void CountLine()
{
ifstream fil("STORY.TXT");
int lines = 0;
char str[80];
while (fil.getline(str, 80))
lines++;
cout << "No. of Lines: " << lines << endl;
fil.close();
}
Topic-2: Data File Handling – Binary File
Question 1: Write the command to place the file pointer at the 10th and 4th record starting position using seekp() or seekg(). File object is “file”, record is “STUDENT”.
file.seekp(9 * sizeof(STUDENT), ios::beg);
file.seekp(3 * sizeof(STUDENT), ios::beg);
Question 2: Output of the following code (sp.dat already contains 2 records):
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, sizeof(s));
if(i.eof()) break;
else cout << "\n" << i.tellg();
}
i.close();
}
void main() {
s.reading();
}
Answer:
42
84
Question 3: Move file pointer to the end of the file “games.dat”
ifile.seekg(0, ios::end);
Question 4: Fill in the blanks (Statement 1 and 2):
class Agency {
int ANo;
char AName[20];
char Mobile[12];
public:
void Enter();
void Disp();
int RAno() { return ANo; }
void UpdateMobile() { /*Function to update 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) {
A.UpdateMobile(); // Statement 1
F.seekg(-1 * sizeof(A), ios::cur); // Statement 2
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();
}
Question 5: 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 Medical {
int RNo; //Representative Code
char Name[20]; //Representative Name
char Mobile[12]; //Representative Mobile
public:
void Input();
void Show();
int RRno() { return RNo; }
void ChangeMobile() { /*Function to change Mobile*/ }
};
void RepUpdate() {
fstream F;
F.open("REP.DAT", ios::binary | 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) {
M.ChangeMobile(); // Statement 1
F.seekp(-1 * sizeof(M), ios::cur); // Statement 2
F.write((char*)&M, sizeof(M));
Change++;
}
}
if (Change) cout << "Mobile Changed for Rep " << URno << endl;
else cout << "Rep not in the Medical" << endl;
F.close();
}
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;
char AName[20];
int Commission;
public:
void Enter();
void Display();
void Update(int c) { Commission = c; }
int GetComm() { return Commission; }
long GetAcode() { return ACode; }
};
void ChangeCommission(long AC, int CM) {
fstream F;
F.open("AGENT.DAT", ios::binary | ios::in | ios::out);
char Changed = 'N';
Agent A;
while (Changed == 'N' && F.read((char*)&A, sizeof(A))) {
if (A.GetAcode() == AC) {
Changed = 'Y';
A.Update(CM);
F.seekg(-1 * sizeof(A), ios::cur); // Statement 1
F.write((char*)&A, sizeof(A)); // Statement 2
}
}
if (Changed == 'N') cout << "Agent not registered.";
F.close();
}
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;
char CName[20];
char Email[30];
public:
void Allocate();
void Show();
void ModifyEmail() { 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 is required to be modified:"; cin >> ChangeCno;
Customer CU;
while (!Change && File.read((char*)&CU, sizeof(CU))) {
if (CU.GetCno() == ChangeCno) {
CU.ModifyEmail();
File.seekp(-1 * sizeof(CU), ios::cur); // Statement 1
File.write((char*)&CU, sizeof(CU)); // Statement 2
Change++;
}
}
if (Change) cout << "Email Modified..." << endl;
else cout << "Customer not found..." << endl;
File.close();
}
Question 8: A binary file “Students.dat” contains data of 10 students. Write the output of the following program segment:
class Student {
int Rno;
char Name[20];
public:
void EnterData() { cin >> Rno; cin.getline(Name, 20); }
void showData() { cout << Rno << " - " << Name << endl; }
};
ifstream file;
Student S;
file.open("Students.dat", ios::binary | ios::in);
file.seekg(0, ios::end);
cout << file.tellg();
Answer:
42
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 GetIno() { 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.GetIno()) {
S.Purchase(PQty);
File.seekp(-sizeof(S), ios::cur); // Statement 1
File.write((char*)&S, sizeof(Stock)); // Statement 2
Success++;
}
}
if (Success == 1) cout << "Purchase Updated" << endl;
else cout << "Wrong Item No" << endl;
File.close();
}
Answer:
Statement 1: File.seekp(-sizeof(S), ios::cur);
Statement 2: 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 == I.GetAno()) {
I.Procure(TQty);
File.seekp(-sizeof(I), ios::cur); // Statement 1
File.write((char*)&I, sizeof(Inventory)); // Statement 2
Found++;
}
}
if (Found == 1) {
cout << "Procurement Updated" << endl;
} else {
cout << "Wrong Article No" << endl;
}
File.close();
}
Answer:
Statement 1: File.seekp(-sizeof(I), ios::cur);
Statement 2: File.write((char*)&I, sizeof(Inventory));
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 beginning 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 words starting with ‘I’ in reverse order. [Delhi, 2015]
void RevText() {
ifstream in("Input.txt");
char word[25];
while (in >> word) {
if (word[0] == 'I')
cout << strrev(word) << " ";
else
cout << word << " ";
}
}
Example: If the content of file is: INDIA IS MY COUNTRY
Output: AIDNI SI MY COUNTRY
Question 3: Write a function in C++ to search and display details, where the destination is “Chandigarh” from the binary file “Flight.Dat”.
class FLIGHT {
int Fno;
char From[20];
char To[20];
public:
char* GetFrom() { return From; }
char* GetTo() { return To; }
void input() { cin >> Fno; gets(From); gets(To); }
void show() { cout << Fno << ":" << From << ":" << To << endl; }
};
void DispDetails() {
ifstream fin("Flight.Dat", ios::binary);
FLIGHT F;
while (fin.read((char*)&F, sizeof(F))) {
if (strcmp(F.GetTo(), "Chandigarh") == 0)
F.show();
}
fin.close();
}
Question 4: Write function definition for TOWER() in C++ to read content of a text file WRITEUP.TXT. Count the presence of the word “TOWER” and display the number of occurrences of this word.
void TOWER() {
int count = 0;
ifstream f("WRITEUP.TXT");
char s[20];
while (f >> s) {
if (strcmpi(s, "TOWER") == 0)
count++;
}
cout << count;
f.close();
}
Question 5: Write 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.
class GIFTS {
int CODE;
char ITEM[20];
float PRICE;
public:
void procure() { cin >> CODE; gets(ITEM); cin >> PRICE; }
void View() { cout << CODE << ":" << ITEM << ":" << PRICE << endl; } float GetPrice() { return PRICE; } }; void COSTLY() { GIFTS G; ifstream fin("GIFTS.DAT", ios::binary); while (fin.read((char*)&G, sizeof(G))) { if (G.GetPrice() > 2000)
G.View();
}
fin.close();
}
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 RECORD: " << POSITION;
MF.close();
}
Output:
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 the word “STORY” and display the number of occurrences.
void SUCCESS() {
int count = 0;
ifstream f("STORY.TXT");
char s[20];
while (f >> s) {
if (strcmpi(s, "STORY") == 0)
count++;
}
cout << count;
f.close();
}
Question 8: Write definition for function Economic() in C++ to read each record of a binary file ITEMS.DAT, find and display those items, which cost less than 2500.
class ITEMS {
int ID;
char GIFT[20];
float cost;
public:
void Get() { cin >> ID; gets(GIFT); cin >> cost; }
void See() { cout << ID << ":" << GIFT << ":" << cost << endl; }
float GetCost() { return cost; }
};
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();
}
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();
}
Output:
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 start with either ‘A’, ‘a’ or ‘B’, ‘b’.
void WORDABSTART() {
ifstream fil;
fil.open("JOY.TXT");
char W[20];
fil >> W;
while (!fil.eof()) {
if (W[0] == 'A' || W[0] == 'a' || W[0] == 'B' || W[0] == 'b')
cout << W << " "; fil >> W;
}
fil.close();
}
Example Output:
apples bananas Ahmedabad buy
Question 11: Write a definition for the function OFFER() in C++ to read each object of a binary file OFFER.DAT, find and display details of those ITEMS, which have status as “ON OFFER”.
class ITEMS {
int ID;
char Item[20];
char Status[20];
float Price;
public:
void GetOnStock() {
cin >> ID;
gets(Item);
gets(Status);
cin >> Price;
}
void view() {
cout << ID << ":" << Item << ":" << Status << ":" << Price << endl;
}
char* IStatus() {
return Status;
}
};
void OFFER() {
ITEMS G;
ifstream fin;
fin.open("OFFER.DAT", ios::binary);
if (!fin) {
cout << "File not found!" << endl;
return;
}
while (fin.read((char*)&G, sizeof(G))) {
if (strcmp(G.IStatus(), "ON OFFER") == 0) {
G.view();
}
}
fin.close();
}
Explanation:
The ITEMS
class has members: ID, Item, Status, and Price.
GetOnStock()
inputs data, view()
displays item details, and IStatus()
returns the status.
OFFER()
opens the binary file OFFER.DAT, reads each record, checks if status is “ON OFFER”, and displays it.
Short Answer Type Questions-II[3 marks each]
Question 1: Read from binary file CAR.DAT and display details of cars with mileage between 100 and 150.
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 << " " << C_Name << " " << Mileage << endl; } float RETURN_Mileage() { return Mileage; } }; void CARSearch() { fstream FIL; FIL.open("CAR.DAT", ios::binary | ios::in); CAR C; bool Found = false; while (FIL.read((char*)&C, sizeof(C))) { if (C.RETURN_Mileage() > 100 && C.RETURN_Mileage() < 150) {
C.display();
Found = true;
}
}
if (!Found)
cout << "Sorry! No car found with mileage between 100 to 150";
FIL.close();
}
Question 2: Display details of players from SPORTS.DAT whose rank is above 500.
class Player {
char PNO[10];
char Name[20];
int rank;
public:
void EnterData() {
gets(PNO);
gets(Name);
cin >> rank;
}
void DisplayData() {
cout << setw(12) << PNO << setw(32) << Name << setw(3) << rank << endl; } int Ret_rank() { return rank; } }; void show() { fstream file; file.open("SPORTS.DAT", ios::binary | ios::in); Player P; while (file.read((char*)&P, sizeof(P))) { if (P.Ret_rank() > 500) {
P.DisplayData();
}
}
file.close();
}
Question 3: Display worker records from WORKER.DAT whose wage is less than 300.
class WORKER {
int WNO;
char WName[30];
float Wage;
public:
void Enter() {
cin >> WNO;
gets(WName);
cin >> Wage;
}
void DISP() {
cout << WNO << " " << WName << " " << Wage << endl;
}
float GetWage() {
return Wage;
}
};
void Display() {
ifstream fin("WORKER.DAT", ios::binary);
WORKER W;
while (fin.read((char*)&W, sizeof(W))) {
if (W.GetWage() < 300)
W.DISP();
}
fin.close();
}
Question 4: Display toys for age range “5 to 8” from binary file TOYS.DAT.
class TOYS {
int ToyCode;
char ToyName[10];
char AgeRange[10];
public:
void Enter() {
cin >> ToyCode;
gets(ToyName);
gets(AgeRange);
}
void Display() {
cout << ToyCode << " " << ToyName << " " << AgeRange << endl;
}
char* WhatAge() {
return AgeRange;
}
};
void READTOYS() {
fstream obj("TOYS.DAT", ios::binary | ios::in);
TOYS T;
while (obj.read((char*)&T, sizeof(T))) {
if (strcmp(T.WhatAge(), "5 to 8") == 0)
T.Display();
}
obj.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 them.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
void WORD4CHAR() {
ifstream fin("FUN.TXT");
char word[50];
while (fin >> word) {
int len = strlen(word);
if (ispunct(word[len - 1])) {
word[len - 1] = '\0';
}
if (strlen(word) == 4) {
cout << word << " ";
}
}
fin.close();
}
Question 2: Write a definition for function ONOFFER() in C++ to read each object of a binary file TOYS.DAT, and display details of those toys which have status as “ON OFFER”.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
class TOYS {
int TID;
char Toy[20], Status[20];
float MRP;
public:
void GetInStock() {
cin >> TID;
cin.ignore();
cin.getline(Toy, 20);
cin.getline(Status, 20);
cin >> MRP;
}
void View() {
cout << TID << " : " << Toy << " : " << MRP << " : " << Status << endl;
}
char* SeeOffer() {
return Status;
}
};
void ONOFFER() {
TOYS T;
ifstream fin("TOYS.DAT", ios::binary);
while (fin.read((char*)&T, sizeof(T))) {
if (strcmp(T.SeeOffer(), "ON OFFER") == 0) {
T.View();
}
}
fin.close();
}
Question 3: Find the output of the following C++ code considering that the binary file CLIENT.DAT exists on the hard disk with 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();
}
Output:
Rec: 1
Rec: 3
Explanation:
Each read()
moves the file pointer by sizeof(C)
. After the first read, it’s at record 1. After three reads, it’s at record 3. Hence, tellg()/sizeof(C)
returns 1 and then 3.