CBSE Class 12 Computer Science Chapter 6: Data File Handling NCERT Solutions

NCERT Solutions PDF Class 12 PDF

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

BoardCBSE
ClassClass 12
SubjectComputer Science
Session2026
LanguageEnglish
TypeNCERT Solutions
Chapter6. 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.

Loading document …
Page of
Loading 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

Solution:

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:

  1. Include necessary headers: <iostream> for input/output and <fstream> for file operations.
  2. Declare an ifstream object named inputFile and associate it with the file "opinion.txt".
  3. Initialize an integer variable count to 0 to store the word count.
  4. Check if the file was opened successfully using inputFile.is_open().
  5. Use a while loop with the condition inputFile >> word. This attempts to read the next word from the file into the word string. The loop continues as long as words can be successfully extracted.
  6. Inside the loop, increment the count for each word read.
  7. After the loop finishes (end of file reached), close the file using inputFile.close().
  8. 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

Solution:

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:

  1. Include necessary headers: <iostream>, <fstream>, <string>, and <cstring> for strlen.
  2. Declare an ifstream object inputFile for "VOWEL.TXT".
  3. Use a character array word to store each word read from the file.
  4. Initialize count to 0.
  5. Open the file and check if it was successful.
  6. Use a while loop (inputFile >> word) to read words.
  7. Inside the loop, use strlen(word) to get the length of the current word.
  8. If the length is exactly 3, increment the count.
  9. 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

Solution:

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:

  1. Include necessary headers: <iostream> and <fstream>.
  2. Declare an fstream object named file and open "NOTES.TXT" in input mode (std::ios::in).
  3. Initialize two integer variables, countA and countE, to 0.
  4. Check if the file was opened successfully.
  5. Use a while loop with file.get(character) to read characters one by one. The loop continues as long as a character is successfully read.
  6. Inside the loop, use an if statement to check if the character is 'A' or 'a'. If it is, increment countA.
  7. Use an else if statement to check if the character is 'E' or 'e'. If it is, increment countE.
  8. After reading the entire file, close it using file.close().
  9. 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?

Q2. What is the purpose of `!i.eof()` in a file reading loop?

Q3. Which function is used to check the length of a C-style string (character array)?

Q4. How can you read a single character from a file in C++?

Q5. When counting alphabets 'A' and 'a' in a file, what is a common approach to handle both cases?

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.