Class 12 Computer Science Practice Assignments: CBSE Class 12 Computer Science Data File Handling In C++ Concepts
Explore structured practice materials through the CBSE Class 12 Computer Science Data File Handling In C++ Concepts. Tailored for Class 12 learners, utilizing these Computer Science assignments ensures thorough preparation and strengthens foundational knowledge before final CBSE evaluations.
Download Data File Handling In C++ Concepts Assignment PDF with Solutions
Access the complete assignment PDF for Class 12 Computer Science below. Regular practice with these targeted academic tasks builds familiarity with standard question patterns and helps secure higher marks in final school evaluations.
DATA FILE HANDLING IN C++
File
• A file is a stream of bytes stored on some secondary storage devices.
• Text file: A text file stores information in readable and printable form. Each line of text is terminated with an EOL (End of Line) character.
• Binary file: A binary file contains information in the non-readable form i.e. in the same format in which it is held in memory.
File Stream
• Stream: A stream is a general term used to name flow of data. Different streams are used to represent different kinds of data flow.
• There are three file I/O classes used for file read / write operations.
• ifstream - can be used for read operations.
• ofstream - can be used for write operations.
• fstream - can be used for both read & write operations.
File modes:
• 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.
• ios::in It open file in input mode(read mode) and permit reading from the file.
• 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.
• ios::ate It open the file in write or read mode, and place file pointer at the end of file i.e input/ output operations can performed anywhere in the file.
• ios::trunc It truncates the existing file (empties the file).
• ios::nocreate If file does not exist this file mode ensures that no file is created and open() fails.
• ios::noreplace If file does not exist, a new file gets created but if the file already exists, the open() fails.
• ios::binary Opens a file in binary mode.
eof(): This function determines the end-of-file by returning true(non-zero) for end of file
otherwise returning false(zero).
close(): This function terminates the connection between the file and stream associated with it.
Stream_object.close(); e.g file.close();
Text File functions:
Char I/O :
· get() – read a single character from text file and store in a buffer.
e.g file.get(ch);
· put() - writing a single character in textfile e.g. file.put(ch);
· getline() - read a line of text from text file store in a buffer.
e.g file.getline(s,80);
· We can also use file>>ch for reading and file<<ch writing in text file. But >> operator
does not accept white spaces.
Binary file functions:
· read()- read a block of binary data or reads a fixed number of bytes from the specified
stream and store in a buffer.
Syntax : Stream_object.read((char *)& Object, sizeof(Object));
e.g file.read((char *)&s, sizeof(s));
· write() – write a block of binary data or writes fixed number of bytes from a specific
memory location to the specified stream.
Syntax : Stream_object.write((char *)& Object, sizeof(Object));
e.g file.write((char *)&s, sizeof(s));
Note:
Both functions take two arguments.
• The first is the address of variable, and the second is the length of that variable in bytes. The address of variable must be type cast to type char*(pointer to character type)
• The data written to a file using write( ) can only be read accurately using read( ).
DATA FILE HANDLING IN C++
File
- A file is a stream of bytes stored on some secondary storage devices.
- Text file: A text file stores information in readable and printable form. Each line of text is terminated with an EOL (End of Line) character.
- Binary file: A binary file contains information in the non-readable form i.e. in the same format in which it is held in memory.
File Stream
- Stream: A stream is a general term used to name flow of data. Different streams are used to represent different kinds of data flow.
- There are three file I/O classes used for file read / write operations:
o ifstream - can be used for read operations.
o ofstream - can be used for write operations.
o fstream - can be used for both read & write operations.
- fstream.h:
o 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.
o It contain predefines set of operation for handling file related input and output, fstream class ties a file to the program for input and output operation.
- A file can be opened using:
o By the constructor method. This will use default streams for file input or output. This method is preferred when file is opened in input or output mode only. Example: ofstream file("student.dat"); or ifstream file("student.dat");
o By the open() member function of the stream. It will preferred when file is opened in various modes i.e ios::in, ios::out, ios::app, ios::ate etc. e.g fstream file; file.open("book.dat", ios::in | ios::out | ios::binary);
File modes:
- 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.
- ios::in: It open file in input mode (read mode) and permit reading from the file.
- 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.
- ios::ate: It open the file in write or read mode, and place file pointer at the end of file i.e input/ output operations can performed anywhere in the file.
- ios::trunc: It truncates the existing file (empties the file).
- ios::nocreate: If file does not exist this file mode ensures that no file is created and open() fails.
- ios::noreplace: If file does not exist, a new file gets created but if the file already exists, the open() fails.
- ios::binary: Opens a file in binary mode.
- eof(): This function determines the end-of-file by returning true(non-zero) for end of file otherwise returning false(zero).
- close(): This function terminates the connection between the file and stream associated with it. Stream_object.close(); e.g file.close();
Text File functions:
- Char I/O:
o get() - read a single character from text file and store in a buffer. e.g file.get(ch);
o put() - writing a single character in textfile e.g. file.put(ch);
o getline() - read a line of text from text file store in a buffer. e.g file.getline(s,80);
- We can also use file>>ch for reading and file<<ch writing in text file. But >> operator does not accept white spaces.
Binary file functions:
- read(): read a block of binary data or reads a fixed number of bytes from the specified stream and store in a buffer.
Syntax: Stream_object.read((char *)& Object, sizeof(Object));
e.g file.read((char *)&s, sizeof(s));
- write(): write a block of binary data or writes fixed number of bytes from a specific memory location to the specified stream.
Syntax: Stream_object.write((char *)& Object, sizeof(Object));
e.g file.write((char *)&s, sizeof(s));
- Note: Both functions take two arguments. The first is the address of variable, and the second is the length of that variable in bytes. The address of variable must be type cast to type char* (pointer to character type). The data written to a file using write() can only be read accurately using read().
File Pointer: The file pointer indicates the position in the file at which the next input/output is to occur.
Moving the file pointer in a file for various operations viz modification, deletion, searching etc. Following functions are used:
- seekg(): It places the file pointer to the specified position in input mode of file. e.g file.seekg(p,ios::beg); or file.seekg(-p,ios::end), or file.seekg(p,ios::cur) i.e to move to p byte position from beginning, end or current position.
- seekp(): It places the file pointer to the specified position in output mode of file. e.g file.seekp(p,ios::beg); or file.seekp(-p,ios::end), or file.seekp(p,ios::cur) i.e to move to p byte position from beginning, end or current position.
- tellg(): This function returns the current working position of the file pointer in the input mode. e.g int p=file.tellg();
- tellp(): This function returns the current working position of the file pointer in the output mode. e.g int p=file.tellp();
Steps To Create A File
- Declare an object of the desired file stream class (ifstream, ofstream, or fstream)
- Open the required file to be processed using constructor or open function.
- Process the file.
- Close the file stream using the object of file stream.
General program structure used for creating a Text File
To create a text file using strings I/O:
#include<fstream.h>
void main()
{
char s[80], ch;
ofstream file("myfile.txt");
do
{
cout<<"\n enter line of text";
gets(s);
file<<s;
cout<<"\n more input y/n";
cin>>ch;
} while(ch!='n' && ch!='N');
file.close();
}
To create a text file using characters I/O:
#include<fstream.h>
void main()
{
char ch;
ofstream file("myfile.txt");
do{
ch=getche();
if (ch==13)
cout<<'\n';
else
file<<ch;
} while(ch!=27);
file.close();
}
Text files in input mode:
To read content of 'myfile.txt' and display it on monitor:
#include<fstream.h>
void main()
{
char ch;
ifstream file("myfile.txt");
while(file)
{
file.get(ch);
cout<<ch;
}
file.close();
}
2 Marks Questions:
Question 1. Write a function in a 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'. [CBSE 2012]
Answer:
void DispDorM()
{
ifstream File("DELHI.TXT");
char str[80];
while(File.getline(str, 80))
{
if(str[0] == 'D' || str[0] == 'M')
cout << str << endl;
}
File.close();
}
In simple words: This function reads a text file line by line and checks if the first character of each line is either 'D' or 'M', displaying only those matching lines.
Exam Tip: Always use getline() to read text files line by line when checking starting characters of text lines.
Question 2. Write a function in a C++ to count the number of lowercase alphabets present in a text file "BOOK.txt".
Answer:
int countalpha()
{
ifstream Fin("BOOK.txt");
char ch;
int count = 0;
while(!Fin.eof())
{
Fin.get(ch);
if (islower(ch))
count++;
}
Fin.close();
return count;
}
In simple words: The function opens the file, reads every character using get(), checks if it is lowercase using islower(), and counts the total.
Exam Tip: Include <ctype.h> header implicitly or explicitly when using library functions like islower().
Question 3. Function to calculate the average word size of a text file.
Answer:
void calculate()
{
fstream File;
File.open("book.txt", ios::in);
char ch;
int sum = 0, n = 0, len = 0;
while(File.get(ch))
{
if(ch == ' ' || ch == '.' || ch == ',' || ch == '\t' || ch == '\n')
{
if(len > 0)
{
sum = sum + len;
n++;
len = 0;
}
}
else
{
len++;
}
}
if(n > 0)
cout << "average word size is " << ((float)sum / n);
File.close();
}
In simple words: This function computes word lengths by tracking delimiters like spaces and punctuation, summing their lengths, and dividing by the total word count.
Exam Tip: Always handle potential division by zero when calculating averages.
Question 4. Assume a text file "coordinate.txt" is already created. Using this file create a C++ function to count the number of words having first character capital.
Answer:
int countword()
{
ifstream Fin("coordinate.txt");
char ch[25];
int count = 0;
while(Fin >> ch)
{
if (isupper(ch[0]))
count++;
}
Fin.close();
return count;
}
In simple words: The extraction operator (>>) reads word by word, and isupper() checks if the first letter of each extracted word is capitalized.
Exam Tip: Using stream extraction (>>) automatically skips whitespace and reads individual words.
Question 5. Function to count number of lines from a text file (a line can have maximum 70 characters or ends at '.')
Answer:
int countword()
{
ifstream Fin("BOOK.txt");
char ch[70];
int count = 0;
if (!Fin)
{
cout << "Error opening file!";
exit(0);
}
while(Fin.getline(ch, 70, '.'))
{
count++;
}
Fin.close();
return count;
}
In simple words: The getline function reads text until a period ('.') or buffer limit is reached, counting each segment as a line.
Exam Tip: getline() takes a delimiter character as an optional third parameter (default is newline).
2/3 Marks Practice Questions
Question 1. Write a function in C++ to count the number of uppercase alphabets present in a text file "BOOK.txt"
Answer:
int countUpper()
{
ifstream fin("BOOK.txt");
char ch;
int count = 0;
while(fin.get(ch))
{
if(isupper(ch))
count++;
}
fin.close();
return count;
}
In simple words: Traverses the file character by character and increments count when isupper() returns true.
Exam Tip: Always close file streams after completing file operations.
Question 2. Write a function in C++ to count the number of alphabets present in a text file "BOOK.txt"
Answer:
int countAlphabets()
{
ifstream fin("BOOK.txt");
char ch;
int count = 0;
while(fin.get(ch))
{
if(isalpha(ch))
count++;
}
fin.close();
return count;
}
In simple words: Uses the isalpha() function to test if each character is an English alphabet letter.
Exam Tip: isalpha() returns non-zero for any uppercase or lowercase letter.
Question 3. Write a function in C++ to count the number of digits present in a text file "BOOK.txt"
Answer:
int countDigits()
{
ifstream fin("BOOK.txt");
char ch;
int count = 0;
while(fin.get(ch))
{
if(isdigit(ch))
count++;
}
fin.close();
return count;
}
In simple words: Uses isdigit() to count all numeric characters (0 through 9) in the file.
Exam Tip: isdigit() checks specifically for characters '0' to '9'.
Question 4. Write a function in C++ to count the number of white spaces present in a text file "BOOK.txt"
Answer:
int countSpaces()
{
ifstream fin("BOOK.txt");
char ch;
int count = 0;
while(fin.get(ch))
{
if(isspace(ch))
count++;
}
fin.close();
return count;
}
In simple words: Uses isspace() to count spaces, tabs, and newline characters.
Exam Tip: isspace() handles all standard whitespace characters automatically.
Question 5. Write a function in C++ to count the number of vowels present in a text file "BOOK.txt"
Answer:
int countVowels()
{
ifstream fin("BOOK.txt");
char ch;
int count = 0;
while(fin.get(ch))
{
char c = tolower(ch);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++;
}
fin.close();
return count;
}
In simple words: Converts each character to lowercase and checks if it matches any of the five vowels.
Exam Tip: Converting to lowercase via tolower() reduces comparison conditions by half.
Question 6. Assume a text file "Test.txt" is already created. Using this file, write a function to create three files "LOWER.TXT" which contains all the lowercase vowels and "UPPER.TXT" which contains all the uppercase vowels and "DIGIT.TXT" which contains all digits.
Answer:
void splitData()
{
ifstream fin("Test.txt");
ofstream f1("LOWER.TXT");
ofstream f2("UPPER.TXT");
ofstream f3("DIGIT.TXT");
char ch;
while(fin.get(ch))
{
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
f1.put(ch);
else if(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
f2.put(ch);
else if(isdigit(ch))
f3.put(ch);
}
fin.close();
f1.close();
f2.close();
f3.close();
}
In simple words: Reads characters from source file and routes them to respective destination files based on conditions.
Exam Tip: Remember to open multiple output streams and close all opened files properly.
General program structure used for operating a Binary File
Program to create a binary file 'student.dat' using structure:
#include<fstream.h>
struct student
{
char name[15];
float percent;
};
void main()
{
ofstream fout;
char ch;
fout.open("student.dat", ios::out | ios::binary);
student s;
if(!fout)
{
cout<<"File can't be opened";
return;
}
do
{
cout<<"\n enter name of student: ";
cin>>s.name;
cout<<"\n enter percentage: ";
cin>>s.percent;
fout.write((char *)&s, sizeof(s));
cout<<"\n more record y/n: ";
cin>>ch;
} while(ch!='n' && ch!='N');
fout.close();
}
Program to read a binary file 'student.dat' display records on monitor:
#include<fstream.h>
struct student
{
char name[15];
float percent;
};
void main()
{
ifstream fin;
student s;
fin.open("student.dat", ios::in | ios::binary);
while(fin.read((char *)&s, sizeof(student)))
{
cout << s.name;
cout << "\n has the percent: " << s.percent << endl;
}
fin.close();
}
Binary file using Objects and other file operations:
Consider the following class declaration then write c++ function for following file operations viz create_file, read_file, add new records, modify record, delete a record, search for a record.
Class definition:
#include<iostream.h>
class student
{
int rno;
char name[30];
int age;
public:
void input()
{
cout<<"\n enter roll no: ";
cin>>rno;
cout<<"\n enter name: ";
gets(name);
cout<<"\n enter age: ";
cin>>age;
}
void output()
{
cout<<"\n roll no: "<<rno;
cout<<"\n name: "<<name;
cout<<"\n age: "<<age;
}
int getrno() { return rno; }
};
1. create_file function:
void create_file()
{
ofstream fout;
char ch;
fout.open("student.dat", ios::out | ios::binary);
student s;
if(!fout)
{
cout<<"File can't be opened";
return;
}
do
{
s.input();
fout.write((char *)&s, sizeof(s));
cout<<"\n more record y/n: ";
cin>>ch;
} while(ch!='n' && ch!='N');
fout.close();
}
2. read_file function:
void read_file()
{
ifstream fin;
student s;
fin.open("student.dat", ios::in | ios::binary);
while(fin.read((char *)&s, sizeof(student)))
{
s.output();
cout<<"\n";
}
fin.close();
}
3. modify_record function:
void modify_record()
{
student s;
fstream file;
file.open("student.dat", ios::in | ios::out | ios::binary);
int r, pos = -1;
cout<<"\n enter the roll no of student whose data to be modified: ";
cin>>r;
while(file.read((char *)&s, sizeof(s)))
{
if (r == s.getrno())
{
cout<<"\n record is: ";
s.output();
pos = file.tellg() - sizeof(s);
break;
}
}
if(pos >= 0)
{
cout<<"\n enter new record: ";
s.input();
file.seekp(pos, ios::beg);
file.write((char *)&s, sizeof(s));
cout<<"\n record modified successfully";
}
else
cout<<"\n record not exist";
file.close();
}
4. delete_record function:
void delete_record()
{
fstream file("student.dat", ios::in | ios::binary);
fstream newfile("newstu.dat", ios::out | ios::binary);
student s;
int r;
cout<<"\n enter the roll no of student whose record to be deleted: ";
cin>>r;
while(file.read((char *)&s, sizeof(s)))
{
if (r != s.getrno())
{
newfile.write((char *)&s, sizeof(s));
}
}
file.close();
newfile.close();
}
5. search_record function:
void search_record()
{
student s;
fstream file;
file.open("student.dat", ios::in | ios::binary);
int r, flag = -1;
cout<<"\n enter the roll no of student whose record to be searched: ";
cin>>r;
while(file.read((char *)&s, sizeof(s)))
{
if (r == s.getrno())
{
cout<<"\n record is: ";
s.output();
flag = 1;
break;
}
}
if(flag == 1)
cout<<"\n search successful";
else
cout<<"\n search unsuccessful";
file.close();
}
1 Mark Questions
Question 1. Observe the program segment carefully and answer the question that follows:
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 PurchaseItem(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);
_______________________ // statement 1
_______________________ // statement 2
success++;
}
}
if (success == 1)
cout<<"Purchase Updated"<<endl;
else
cout<<"Wrong Item No"<<endl;
File.close();
}
Answer:
i) Statement 1 to position the file pointer to the appropriate place so that the data updation is done for the required item:
File.seekp(File.tellg() - sizeof(Stock)); OR File.seekp(-sizeof(Stock), ios::cur);
ii) Statement 2 to perform write operation so that the updation is done in the binary file:
File.write((char *)&s, sizeof(s)); OR File.write((char *)&s, sizeof(Stock));
In simple words: After reading a record and modifying it in memory, we must reposition the put pointer backward by one object size and overwrite the record using write().
Exam Tip: Always remember that read() moves the get pointer forward, so seekp() is required before writing back to the exact same position.
3 Marks Question
Question 2. Write a function in c++ to search for details (Phoneno and Calls) of those Phones which have more than 800 calls from binary file "phones.dat". Assuming that this binary file contains records/ objects of class Phone, which is defined below. [CBSE 2012]
class Phone
{
char Phoneno[10];
int Calls;
public:
void Get() { gets(Phoneno); cin>>Calls; }
void Billing() { cout<<Phoneno<<"#"<<Calls<<endl; }
int GetCalls() { return Calls; }
};
Answer:
void Search()
{
Phone P;
ifstream fin;
fin.open("phones.dat", ios::binary | ios::in);
while(fin.read((char *)&P, sizeof(P)))
{
if(P.GetCalls() > 800)
P.Billing();
}
fin.close();
}
In simple words: This function opens the phone records file in binary input mode, checks each phone object's call count, and calls billing() if it exceeds 800.
Exam Tip: When reading binary files, pass the address of the object cast to (char*) and sizeof the object.
Question 3. Write a function in C++ to add new objects at the bottom of a binary file "STUDENT.DAT", assuming the binary file is containing the objects of the following class.
class STUD
{
int Rno;
char Name[20];
public:
void Enter() { cin>>Rno; gets(Name); }
void Display() { cout<<Rno<<Name<<endl; }
int getRno() { return Rno; }
};
Answer:
void addRecord()
{
ofstream fout;
fout.open("STUDENT.DAT", ios::binary | ios::app);
STUD s;
s.Enter();
fout.write((char *)&s, sizeof(s));
fout.close();
}
In simple words: Opens the binary file in append mode (ios::app) so new records are automatically added at the end without overwriting existing data.
Exam Tip: Use ios::app for appending records to preserve existing binary file contents.
Question 4. Given a binary file PHONE.DAT, containing records of the following class type:
class Phonlist
{
char name[20];
char address[30];
char areacode[5];
char Phoneno[15];
public:
void Register();
void Show();
int CheckCode(char AC[])
{
return(strcmp(areacode, AC));
}
};
Write a function TRANSFER() in C++, that would copy all those records which are having areacode as "DEL" from PHONE.DAT to PHONBACK.DAT.
Answer:
void TRANSFER()
{
fstream File1, File2;
Phonelist P;
File1.open("PHONE.DAT", ios::binary | ios::in);
File2.open("PHONBACK.DAT", ios::binary | ios::out);
while(File1.read((char *)&P, sizeof(P)))
{
if(P.CheckCode("DEL") == 0)
{
File2.write((char *)&P, sizeof(P));
}
}
File1.close();
File2.close();
}
In simple words: This function reads records from PHONE.DAT, checks if CheckCode returns 0 (indicating a match with "DEL"), and writes matching records to PHONBACK.DAT.
Exam Tip: strcmp() returns 0 when two strings are equal, so check against 0 when verifying matching codes.
Free study material for Computer Science
Download Practice Assignments: Class 12 Computer Science Data File Handling In C++ Concepts
Chapter Practice Questions for Class 12 Computer Science
Explore reliable practice questions for Data File Handling In C++ Concepts tailored for Class 12 learners. Use these structured worksheets to evaluate preparedness and strengthen core problem-solving skills.
Why Practice Class 12 Computer Science Assignments?
- Curriculum Standards: Assignments match modern CBSE sample formats to ensure relevant preparation.
- Thorough Revision: Detailed problem sets reinforce core concepts and eliminate conceptual weak spots.
- Execution Speed: Timed practice with assignment sets sharpens overall response timing.
How to Approach Computer Science Data File Handling In C++ Concepts Assignments
- Concept Foundation: Review the NCERT book for Class 12 Computer Science thoroughly before diving into assignment tasks.
- Self-Evaluation: Solve exercises independently before inspecting professional answer guides.
- Progress Monitoring: Note down complex formulas or concepts, clearing them up using available online practice aids.
FAQs
You can download free PDF assignments for Class 12 Computer Science Data File Handling In C++ Concepts from StudiesToday.com. These practice sheets have been updated for the 2026-27 session covering all concepts from latest NCERT textbook.
Yes, our teachers have given solutions for all questions in the Class 12 Computer Science Data File Handling In C++ Concepts assignments. This will help you to understand step-by-step methodology to get full marks in school tests and exams.
Yes. These assignments are designed as per the latest CBSE syllabus for 2026. We have included huge variety of question formats such as MCQs, Case-study based questions and important diagram-based problems found in Data File Handling In C++ Concepts.
Practicing topicw wise assignments will help Class 12 students understand every sub-topic of Data File Handling In C++ Concepts. Daily practice will improve speed, accuracy and answering competency-based questions.
Yes, all printable assignments for Class 12 Computer Science Data File Handling In C++ Concepts are available for free download in mobile-friendly PDF format.