Q.A text file named MESSAGE.TXT contains some text. Another text file named SMS.TXT needs to be created such that it would store only the first 150 characters from the file MESSAGE.TXT. Write a user-defined function LongToShort() in C++ that would perform the above task of creating SMS.TXT from the already existing file MESSAGE.TXT.
🔒You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
🔒 Start your 14-day free trial to unlock the full solution →Part (a)Concept understanding — File Input Output Filtering
File Input Output Filtering
Think of a water filter. You pour in tap water, and what comes out is cleaner, purer, and ready to drink. The filter doesn't create new water — it takes what's already there and transforms it by removing impurities or adding something useful.
File Input Output Filtering works on the same principle. It is a way of processing data as it moves from one place to another — typically from an input source (like a file or keyboard) to an output destination (like a file or screen). The "filter" sits in between, reading the incoming data, modifying it in some way, and then writing the modified version out.
The Core Idea
At its simplest, a filter takes a stream of data, performs a transformation on it, and produces a new stream. The transformation could be anything: converting all letters to uppercase, removing blank lines, replacing one word with another, or rearranging the order of records.
The key insight is that the filter does not care where the data came from or where it is going. It only cares about what to do with the data as it passes through. This makes filters reusable — the same filter can work on data from a file, from a user typing at a keyboard, or from the output of another program.
Why It Matters
In the real world, data rarely arrives in the exact format you need. A bank might receive transaction records with dates written as "2024-03-15" but their system expects "15 March 2024". A school might get student lists with names in lowercase but needs them capitalised. A business might export a report with extra blank lines that clutter the final document.
Instead of rewriting entire programs for each of these situations, you can use filters. You take the raw data, run it through the appropriate filter, and get exactly what you need on the other side.
How It Works in Practice
A filter typically follows a simple pattern:
- Read one piece of data (a line, a character, a record)
- Process it according to the rule
- Write the result
- Repeat until there is no more data
This is called a "loop" — the filter keeps doing the same thing over and over until the input runs out. Because it processes data piece by piece rather than loading everything into memory at once, it can handle enormous files without slowing down.
This "read-process-write" cycle is why filters are so efficient. A filter that converts a million-line file to uppercase never holds more than one line in memory at a time. It reads a line, converts it, writes it, and moves on.
Common Types of Filters
Filters can be grouped by what they do to the data:
Transformation filters change the content itself. Converting text to uppercase, replacing British spellings with American ones, or encrypting sensitive information are all transformations.
Selection filters choose which pieces of data to keep and which to discard. A filter that removes all lines containing the word "ERROR" is a selection filter — it lets some data through and blocks the rest.
Formatting filters change the appearance or structure without altering the meaning. Adding line numbers to a document, aligning columns, or inserting page breaks are formatting operations.
Combination filters do more than one thing. A filter might remove blank lines, convert everything to lowercase, and then add a timestamp to each line — all in a single pass.
The Chain Concept
The real power of filtering emerges when you connect filters together. The output of one filter becomes the input to the next. This is called a "pipeline" or "chain."
Imagine you have a raw data file with messy entries. You could:
- First filter: remove blank lines
- Second filter: convert all text to uppercase
- Third filter: sort the lines alphabetically
- Fourth filter: add line numbers
Each filter does one simple job. Together, they produce a clean, numbered, sorted, uppercase document from the original mess. You can rearrange, add, or remove filters without changing any of them individually.
The principle of "one job, done well" is central to filtering. A filter that tries to do everything becomes complex and brittle. A filter that does one thing can be combined with others to achieve almost any result.
A Concrete Example Without Numbers …
Part (b)Concept understanding — File Input Output Filtering
File Input Output Filtering
Think of a water filter. You pour in tap water, and what comes out is cleaner, purer, and ready to drink. The filter doesn't create new water — it takes what's already there and transforms it by removing impurities or adding something useful.
File Input Output Filtering works on the same principle. It is a way of processing data as it moves from one place to another — typically from an input source (like a file or keyboard) to an output destination (like a file or screen). The "filter" sits in between, reading the incoming data, modifying it in some way, and then writing the modified version out.
The Core Idea
At its simplest, a filter takes a stream of data, performs a transformation on it, and produces a new stream. The transformation could be anything: converting all letters to uppercase, removing blank lines, replacing one word with another, or rearranging the order of records.
The key insight is that the filter does not care where the data came from or where it is going. It only cares about what to do with the data as it passes through. This makes filters reusable — the same filter can work on data from a file, from a user typing at a keyboard, or from the output of another program.
Why It Matters
In the real world, data rarely arrives in the exact format you need. A bank might receive transaction records with dates written as "2024-03-15" but their system expects "15 March 2024". A school might get student lists with names in lowercase but needs them capitalised. A business might export a report with extra blank lines that clutter the final document.
Instead of rewriting entire programs for each of these situations, you can use filters. You take the raw data, run it through the appropriate filter, and get exactly what you need on the other side.
How It Works in Practice
A filter typically follows a simple pattern:
- Read one piece of data (a line, a character, a record)
- Process it according to the rule
- Write the result
- Repeat until there is no more data
This is called a "loop" — the filter keeps doing the same thing over and over until the input runs out. Because it processes data piece by piece rather than loading everything into memory at once, it can handle enormous files without slowing down.
This "read-process-write" cycle is why filters are so efficient. A filter that converts a million-line file to uppercase never holds more than one line in memory at a time. It reads a line, converts it, writes it, and moves on.
Common Types of Filters
Filters can be grouped by what they do to the data:
Transformation filters change the content itself. Converting text to uppercase, replacing British spellings with American ones, or encrypting sensitive information are all transformations.
Selection filters choose which pieces of data to keep and which to discard. A filter that removes all lines containing the word "ERROR" is a selection filter — it lets some data through and blocks the rest.
Formatting filters change the appearance or structure without altering the meaning. Adding line numbers to a document, aligning columns, or inserting page breaks are formatting operations.
Combination filters do more than one thing. A filter might remove blank lines, convert everything to lowercase, and then add a timestamp to each line — all in a single pass.
The Chain Concept
The real power of filtering emerges when you connect filters together. The output of one filter becomes the input to the next. This is called a "pipeline" or "chain."
Imagine you have a raw data file with messy entries. You could:
- First filter: remove blank lines
- Second filter: convert all text to uppercase
- Third filter: sort the lines alphabetically
- Fourth filter: add line numbers
Each filter does one simple job. Together, they produce a clean, numbered, sorted, uppercase document from the original mess. You can rearrange, add, or remove filters without changing any of them individually.
The principle of "one job, done well" is central to filtering. A filter that tries to do everything becomes complex and brittle. A filter that does one thing can be combined with others to achieve almost any result.
A Concrete Example Without Numbers …
Both parts are text-file filtering tasks in C++ using <fstream>.
Part (a)
Copy only the first 150 characters of MESSAGE.TXT into a new file SMS.TXT.
#include <fstream>
void LongToShort() {
ifstream fin("MESSAGE.TXT");
ofstream fout("SMS.TXT");
char ch;
int count = 0;
while (count < 150 && fin.get(ch)) { // stop at 150 or EOF
fout.put(ch);
count++;
}
fin.close();
fout.close();
}
``` …
Part (a): copy the first 150 characters of MESSAGE.TXT into SMS.TXT. Part (b): print each word of CONTENTS.TXT longer than 9 letters (Conditional statements programming).
C++ file handling uses ifstream for reading and ofstream for writing, both from <fstream>. The two alternatives share the read-then-filter pattern.
Part (a)
We must transfer only the first 150 characters. Read a character at a time; the loop stops either when 150 characters have been written or when get() fails at end-of-file.
#include <iostream>
#include <fstream>
using namespace std;
void LongToShort() {
ifstream fin("MESSAGE.TXT");
ofstream fout("SMS.TXT");
if (!fin) { cout << "Cannot open MESSAGE.TXT"; return; }
char ch;
int count = 0;
while (count < 150 && fin.get(ch)) {
fout.put(ch);
count++;
}
fin.close();
fout.close();
}
``` …
- CBSE 2020Set 91/D2 marksQ.Write a function Show_words() in Python to read the content of a text file 'NOTES.TXT' and display the entire content in capital letters. Example, if the file contains: "This is a test file" Then the function should display the output as: THIS IS A TEST FILE(OR)Write a function Show_words() in Python to read the content of a text file 'NOTES.TXT' and display only such lines of the file which have exactly 5 words in them. Example, if the file contains: This is a sample file. The file contains many sentences. But needs only sentences which have only 5 words. Then the function should display the output as: This is a sample file. The file contains many sentences :
›Reveal solutionSolution
Part (a): read the whole file and print it in uppercase (
upper()).Part (b): print only the lines that contain exactly 5 words (
len(line.split())==5).Part (a)
Open
NOTES.TXTin read mode, read its entire content withread(), convert to capitals with the string methodupper(), and print it. Thewithblock closes the file automatically.def Show_words(): with open('NOTES.TXT', 'r') as f: content = f.read() print(content.upper())For
This is a test file:THIS IS A TEST FILE … - CBSE 2019Set 91/42 marksQ.Write a user-defined function TotalPrice() in C++ to read each object of a binary file STOCK.DAT, and display the Name from all such records whose Price is above 150. Assume that the file STOCK.DAT is created with the help of objects of class Stock, which is defined below: class Stock { char Name[20]; float Price; public: char* RName() { return Name; } float RPrice() { return Price; } };(OR)A binary file DOCTORS.DAT contains records stored as objects of the following class: class Doctor { int DNo; char Name[20]; float Fees; public: int *GetNo() { return DNo; } void Show() { cout<<Dno<<" * " <<Name<< " * " <<Fees<<endl;} }; Write definition for function Details(int N) in C++, which displays the details of the Doctor from the file DOCTORS.DAT, whose DNo matches with the parameter N passed to the function.
›Reveal solutionSolution
Part (a):
TotalPrice()reads STOCK.DAT and prints the Name of every item with Price > 150.Part (b):
Details(int N)reads DOCTORS.DAT and shows the doctor whose DNo equals N.Both functions use binary file input with filtering: open with
ios::binary, read whole objects withread((char*)&obj, sizeof(obj))in awhileloop (the stream is false at end of file), test a condition, and output the matches.Part (a)
The
Stockclass exposesRName()andRPrice(). Read each object and print the name when the price is above 150.void TotalPrice() { ifstream fin("STOCK.DAT", ios::binary); Stock S; while (fin.read((char*)&S, sizeof(S))) { if (S.RPrice() > 150) cout << S.RName() << endl; } fin.close(); } ``` … - CBSE 2019Set 91/42 marksQ.Write a method/function ISTOUPCOUNT() in python to read contents from a text file WRITER.TXT, to count and display the occurrence of the word "IS" or "TO" or "UP". For example : If the content of the file is IT IS UP TO US TO TAKE CARE OF OUR SURROUNDING. IT IS NOT POSSIBLE ONLY FOR THE GOVERNMENT TO TAKE RESPONSIBILITY The method/function should display Count of IS TO and UP is 6(OR)Write a method/function AEDISP() in python to read lines from a text file WRITER.TXT, and display those lines, which are starting either with A or starting with E. For example : If the content of the file is A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH. WE SHOULD TAKE CARE OF OUR ENVIRONMENT. EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD. The method should display A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH. EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD.
›Reveal solutionSolution
Part (a): ISTOUPCOUNT() counts words equal to "IS"/"TO"/"UP" and prints
Count of IS TO and UP is 6for the sample.Part (b): AEDISP() prints only the lines that begin with 'A' or 'E'.
Part (a)
Read the whole file, break it into words with
split(), and test each word against the setIS,TO,UP. (The check is on whole words, soUPWARDwould not count asUP.)def ISTOUPCOUNT(): f = open("WRITER.TXT", "r") data = f.read() f.close() count = 0 for word in data.split(): if word in ("IS", "TO", "UP"): count += 1 print("Count of IS TO and UP is", count)For the sample content
IT IS UP TO US TO TAKE CARE ... GOVERNMENT TO TAKE RESPONSIBILITY, the matches are IS (2), TO (3), UP (1) = 6:Count of IS TO and UP is 6 …
🎓Unlock everything free for 14 days
- ✓Full step-by-step solutions
- ✓Concept-first explanations
- ✓Methods, shortcuts & mistakes
- ✓PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.