CBSE Class 12 Computer Science Chapter 6: Data File Handling NCERT Solutions
This chapter delves into Data File Handling in C++, focusing on text files. Students will learn how to perform essential operations like reading from and writing to files. The NCERT Solutions cover practical examples such as counting words in a file, identifying words of a specific length, and counting the occurrences of particular characters. These solutions provide step-by-step guidance, helping students understand the logic behind file manipulation in C++. Mastering these concepts is crucial for developing programs that interact with external data sources and for effective exam revision.
Quick info
| Board | CBSE |
|---|---|
| Class | Class 12 |
| Subject | Computer Science |
| Session | 2026 |
| Language | English |
| Type | NCERT Solutions |
| Chapter | 6. Data File Handling |
Chapter summary
Chapter 6, 'Data File Handling,' focuses on text file operations in C++. It covers fundamental concepts like opening, reading, and closing files. The provided NCERT Solutions offer practical implementations for tasks such as counting total words, counting words of a specific length, and tallying the occurrences of specific alphabets within a text file. These exercises reinforce the understanding of file I/O streams and character-by-character processing.
Learning outcomes
- Understand the basics of text file handling in C++.
- Implement functions to count words in a text file.
- Develop programs to count words of a specific length.
- Write code to count the occurrences of specific characters in a file.
- Apply file input/output operations for data processing.
Topics covered
Paper topics
- Text File Handling
- File Input/Output Streams
- Opening and Closing Files
- Reading from Files
- Counting Words in a File
- Counting Words of Specific Length
- Counting Character Occurrences
- C++ File I/O Functions
Important topics
- Text File Operations
- Word Counting Logic
- Character Counting Logic
- File Stream Classes (`ifstream`, `fstream`)
- Looping through File Content
PDF preview
Read page by page below. PDF is streamed from the official NCERT website — no download button on this page.
Questions and Solutions
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 the 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
To count the words in a text file, we can read the file word by word and increment a counter for each word read. The extraction operator (>>) in C++ reads whitespace-separated strings, which naturally separates words.
Here is the C++ function:
#include <iostream>
#include <fstream>
#include <string>
void word_count() {
std::ifstream inputFile("opinion.txt");
std::string word;
int count = 0;
if (inputFile.is_open()) {
// Read words until the end of the file is reached
while (inputFile >> word) {
count++; // Increment count for each word successfully read } inputFile.close();
std::cout << "Total number of words present in the text file are: " << count << std::endl;
} else {
std::cout << "Error opening file." << std::endl; } }
Explanation:
- Include necessary headers:
<iostream>for input/output and<fstream>for file operations. - Declare an
ifstreamobject namedinputFileand associate it with the file "opinion.txt". - Initialize an integer variable
countto 0 to store the word count. - Check if the file was opened successfully using
inputFile.is_open(). - Use a
whileloop with the conditioninputFile >> word. This attempts to read the next word from the file into thewordstring. The loop continues as long as words can be successfully extracted. - Inside the loop, increment the
countfor each word read. - After the loop finishes (end of file reached), close the file using
inputFile.close(). - Finally, display the total word count.
Question 2
Write a function in C++ to count and display the number 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
This function will read the file word by word, check the length of each word, and count only those that have exactly three letters. The strlen() function is used to determine the length of each word.
Here is the C++ function:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring> // For strlen
void countThreeLetterWords() {
std::ifstream inputFile("VOWEL.TXT");
char word[80]; // Buffer to store each word
int count = 0;
if (inputFile.is_open()) {
// Read words until the end of the file
while (inputFile >> word) {
// Check if the length of the word is exactly 3
if (strlen(word) == 3) {
count++; // Increment count if it's a three-letter word } }
inputFile.close();
std::cout << "Number of three-letter words = " << count << std::endl;
} else {
std::cout << "Error opening file." << std::endl; } }
Explanation:
- Include necessary headers:
<iostream>,<fstream>,<string>, and<cstring>forstrlen. - Declare an
ifstreamobjectinputFilefor "VOWEL.TXT". - Use a character array
wordto store each word read from the file. - Initialize
countto 0. - Open the file and check if it was successful.
- Use a
whileloop (inputFile >> word) to read words. - Inside the loop, use
strlen(word)to get the length of the current word. - If the length is exactly 3, increment the
count. - Close the file and display the final count.
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 follows: CBSE enhanced its CCE guidelines further. The AECount() function should display the output as A:1 E:7
This function reads the file character by character and checks if each character is either 'A'/'a' or 'E'/'e'. It maintains separate counters for both.
Here is the C++ function:
#include <iostream>
#include <fstream>
void AECount() {
std::fstream file("NOTES.TXT", std::ios::in);
char character;
int countA = 0;
int countE = 0;
if (file.is_open()) {
// Read characters one by one until end of file
while (file.get(character)) {
// Check for 'A' or 'a'
if (character == 'A' || character == 'a') {
countA++; } // Check for 'E' or 'e'
else if (character == 'E' || character == 'e') {
countE++; } }
file.close();
std::cout << "A: " << countA << " E: " << countE << std::endl;
} else {
std::cout << "Error opening file." << std::endl; } }
Explanation:
- Include necessary headers:
<iostream>and<fstream>. - Declare an
fstreamobject namedfileand open "NOTES.TXT" in input mode (std::ios::in). - Initialize two integer variables,
countAandcountE, to 0. - Check if the file was opened successfully.
- Use a
whileloop withfile.get(character)to read characters one by one. The loop continues as long as a character is successfully read. - Inside the loop, use an
ifstatement to check if the character is 'A' or 'a'. If it is, incrementcountA. - Use an
else ifstatement to check if the character is 'E' or 'e'. If it is, incrementcountE. - After reading the entire file, close it using
file.close(). - Display the final counts for 'A' and 'E'.
Common mistakes
- Incorrectly handling file opening and closing operations.
- Errors in loop conditions for reading file content (e.g., not checking for end-of-file properly).
- Issues with string manipulation functions like `strlen`.
- Case-sensitivity errors when comparing characters.
Revision tips
- Practice writing C++ functions for various file reading tasks.
- Pay close attention to loop termination conditions when processing files.
- Ensure correct use of file stream objects (`ifstream`, `ofstream`, `fstream`).
- Test your code with different file contents, including empty files and files with special characters.
Practice MCQs
Q1. Which C++ stream class is typically used for reading from text files?
Explanation: The `ifstream` class is specifically designed for input operations, making it the standard choice for reading data from files.
Q2. What is the purpose of `!i.eof()` in a file reading loop?
Explanation: The `eof()` function returns true if the end-of-file has been reached. `!i.eof()` ensures the loop continues as long as the end of the file has not been encountered.
Q3. Which function is used to check the length of a C-style string (character array)?
Explanation: The `strlen()` function from the `<cstring>` (or `<string.h>`) library is used to calculate the length of a null-terminated string.
Q4. How can you read a single character from a file in C++?
Explanation: The `get()` member function of file stream objects reads a single character, including whitespace characters.
Q5. When counting alphabets 'A' and 'a' in a file, what is a common approach to handle both cases?
Explanation: The most straightforward way is to include conditions for both the uppercase ('A') and lowercase ('a') versions in the `if` statement.
Frequently asked questions
What are the primary operations covered in Chapter 6 of CBSE Class 12 Computer Science?
Chapter 6 focuses on Data File Handling, specifically text files. It covers reading data from files, counting words, counting words of a specific length, and counting the occurrences of specific characters.
Which C++ libraries are essential for file handling?
The `<fstream>` library is essential for file stream operations. For string manipulation like checking length, the `<cstring>` library (for `strlen`) is often used.
How do the NCERT Solutions help in preparing for exams?
These solutions provide clear, step-by-step explanations and rewritten code for each question, reinforcing understanding of file handling concepts and C++ implementation, which is crucial for exam success.
What is the difference between `ifstream` and `ofstream`?
`ifstream` is used for input operations (reading from files), while `ofstream` is used for output operations (writing to files). `fstream` can be used for both.
How can I ensure my file reading loop terminates correctly?
You should use a condition like `while (!file.eof())` or check the stream state after each read operation to ensure the loop stops precisely when the end of the file is reached, preventing potential errors.
Content reviewed by the NCERT Help team. Editorial Team and update policy
NCERT Solutions PDF PDF on NCERT Help. URL unchanged for search indexing.