Q.Find the output of the following C++ code considering that the binary file STOCK.DAT exists on the hard disk with the following 5 records for the class STOCK containing Name and Price. Name Price Rice 110 Wheat 60 Cheese 200 Pulses 170 Sauce 150 void main() { fstream File; File.open("STOCK.DAT",ios::binary|ios::in); Stock S; for (int I=1; I<=2; I++) { File.seekg((2*I-1)sizeof(S)); File.read((char)&S, sizeof(S)); cout << "Read : " << File.tellg()/sizeof(S)<< endl; } File.close(); }
🔒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 Handling Methods
File Handling Methods: A First Look
Think about the last time you saved a document on your computer. You clicked "Save," gave it a name, and later opened it again to continue working. That simple act—storing information so you can retrieve it later—is the entire reason file handling exists. Every time you work with a file, whether it's a Word document, a PDF, or even a photo, you are performing file handling.
At its core, file handling is the process of creating, reading, updating, and deleting files through a computer program. It is how a program talks to the storage on your machine—the hard drive or SSD—rather than just working with data that disappears when you close the program.
The Two Fundamental Modes
When a program wants to work with a file, it must first open that file. Opening a file is like unlocking a drawer: you decide what you want to do with it before you start. There are two basic intentions:
- Reading – You want to look at the contents of the file without changing anything. The file stays exactly as it is.
- Writing – You want to put new content into the file, either by starting fresh (overwriting everything) or by adding to what is already there (appending).
These two intentions define the mode in which you open the file. A file opened for reading cannot be written to, and a file opened for writing cannot be read from—at least not in the simplest approach. This separation exists to prevent accidents: you do not want a program that is supposed to only display your data to accidentally erase it.
In many programming languages, you can open a file in "read and write" mode, but that is a more advanced technique. For a beginner, think of reading and writing as two separate keys that open different locks on the same drawer.
The Lifecycle of a File Operation
Every file handling operation follows a fixed sequence. You cannot skip a step without causing trouble.
- Open the file – You tell the program which file you want and what you intend to do with it (read or write). The program checks whether the file exists (for reading) or whether it can create a new one (for writing).
- Perform the operation – You either read the data from the file into your program's memory, or you write data from your program into the file. This step can happen many times—you might read one line, then another, then another.
- Close the file – You tell the program you are done. This step is crucial. Closing a file saves any changes you made and frees up the file so other programs can use it.
Forgetting to close a file is like leaving a tap running. The file may remain locked, data might not be saved properly, and your program could waste memory. Always close what you open.
Why This Matters for a Commerce or Humanities Student
You might wonder why a student of commerce or humanities needs to understand file handling. The answer is simple: almost every modern business, government office, and research project deals with data stored in files.
- A commerce student analyzing sales records will need to read data from a spreadsheet file, process it, and write the results to a new file.
- A humanities student working with historical documents might need to read text files containing old letters, clean up the formatting, and save the cleaned version.
- Anyone managing a database or a website will encounter file handling when uploading images, generating reports, or backing up information. …
Part (b)Concept understanding — File Access Modes
Imagine you have a physical diary or a notebook. You can do different things with it: you can open it to write new entries, you can open it just to read what you already wrote, or you can open it to add a new page at the end. You might also want to open it in a way that prevents anyone else from writing in it while you are reading. These different ways of "opening" the notebook are exactly what File Access Modes are for a computer file.
A file access mode is simply the permission you request from the operating system when you tell it you want to work with a file. It is a rule that says, "I want to open this file, and here is exactly what I plan to do with it." The operating system then checks if you are allowed to do that, and if you are, it sets up the file accordingly.
The most fundamental modes are three, and they mirror your notebook perfectly:
- Read Mode (
r): You can only look at the contents. You cannot change a single character. This is like opening your notebook to study for an exam — you read, but you do not write. If the file does not exist, the operating system will tell you it cannot find it (an error). - Write Mode (
w): You can write new content, but here is the critical point — it starts from a blank page. Opening a file in write mode is like tearing out all the existing pages of your notebook and then writing fresh. It destroys whatever was there before. If the file does not exist, the system will create a brand new empty notebook for you. - Append Mode (
a): You can write new content, but only at the very end of the file. This is like adding a new page at the back of your notebook. Everything you wrote earlier stays untouched. If the file does not exist, the system creates a new one, just like in write mode.
The key difference between Write and Append is preservation. Write erases the past; Append protects it. If you are logging daily sales data, you would use Append so yesterday's numbers are not lost. If you are creating a new report from scratch, you use Write.
There is also a very common fourth mode that combines reading and writing: …
Part (a)
Let s = sizeof(S).
- I=1:
seekg(1*s)→ get-pointer at record 1; afterread, pointer = 2s;tellg()/s = 2→Read : 2. - I=2:
seekg(3*s)→ pointer at record 3; afterread, pointer = 4s;tellg()/s = 4→Read : 4.
Read : 2
Read : 4 …
Part (a): the loop repositions and reads, printing Read : 2 then Read : 4. Part (b): seekg() moves the get-pointer to a position, whereas tellg() reports the get-pointer's current position.
Part (a)
Let s = sizeof(S) be the size of one STOCK record. seekg(pos) moves the get-pointer to byte pos, read(...) then reads one record (advancing the pointer by s), and tellg() returns the current byte offset.
- I = 1:
seekg((2·1−1)*s) = seekg(1*s)→ pointer at start of record index 1.readconsumes one record → pointer now at2*s.tellg()/sizeof(S) = 2s/s = 2→ printsRead : 2. - I = 2:
seekg((2·2−1)*s) = seekg(3*s)→ pointer at start of record index 3.read→ pointer at4*s.tellg()/sizeof(S) = 4s/s = 4→ printsRead : 4.
Read : 2
Read : 4 …
- CBSE 2026Set 91/41 markMCQQ.Consider the statement given below : f1 = open("pqr.dat","________") Which of the following is the correct file mode to open the file in read only mode ? (A) a (B) rb (C) r+ (D) rb+
›Reveal solutionSolution
To open a file in read-only mode, the correct file mode is
"r"— but among the given options,"rb"is the only one that opens a file for reading (in binary mode), making it the correct choice.When you work with files in Python, the mode string you pass to the
open()function determines exactly what you can do with that file — read, write, append, or a combination. The question asks specifically for read-only mode, which means the file should be opened only for reading, not for writing or appending.Let's look at each option:
-
(A)
"a"— This stands for append mode. It opens the file for writing, but data is added at the end of the file. It is not read-only at all. In fact, if the file does not exist,"a"creates a new one. So this is incorrect. -
(B)
"rb"— The"r"means read, and the"b"means binary mode. Together,"rb"opens the file for reading in binary format. This is indeed a read-only mode — you cannot write to the file. Among the given options, this is the correct one. -
(C)
"r+"— The"+"adds both reading and writing. So"r+"opens the file for both reading and writing. It is not read-only; you can modify the file. Hence, it is incorrect for the given requirement. -
(D)
"rb+"— This combines binary mode with read-write access. Like"r+", it allows both reading and writing, just in binary format. So it is also not read-only. …
-
- CBSE 2024Set 91/41 markMCQQ.Consider the following Python statement: F=open('CONTENT.TXT') Which of the following is an invalid statement in Python? (A) F.seek(1,0) (B) F.seek(0,1) (C) F.seek(0,-1) (D) F.seek(0,2)
›Reveal solutionSolution
The
seek()method in Python's file handling allows you to change the current position of the file pointer, but itswhenceargument, which specifies the reference point, must be one of three specific integer values: 0 (beginning), 1 (current position), or 2 (end of file).In Python, interacting with files is a fundamental aspect of many programs, allowing us to store and retrieve data persistently. The statement
F = open('CONTENT.TXT')is the first step in this process. It opens a file namedCONTENT.TXTin the default read mode ('r') and returns a file object, which we've assigned to the variableF. This file object acts as a gateway, providing methods to perform operations like reading, writing, and, importantly, navigating within the file.One crucial method for navigating within a file is
seek(). Imagine a cursor in a text editor;seek()allows you to move this cursor to a specific location within the file. This is incredibly useful when you need to re-read a part of a file, skip certain sections, or write data at a precise point.The
seek()method takes two arguments:seek(offset, whence).- The
offsetargument specifies the number of bytes to move. This can be a positive or negative integer, depending on thewhenceargument. - The
whenceargument determines the reference point from which theoffsetis calculated. This is where the strict rules apply, and understanding these values is key to usingseek()correctly.
There are only three valid integer values for
whence:0(oros.SEEK_SET): This means theoffsetis relative to the beginning of the file. Whenwhenceis 0, theoffsetmust be a non-negative integer, as you cannot move before the start of the file.1(oros.SEEK_CUR): This means theoffsetis relative to the current file position. Theoffsetcan be positive (to move forward) or negative (to move backward) from the current position.2(oros.SEEK_END): This means theoffsetis relative to the end of the file. Whenwhenceis 2, theoffsetis typically a non-positive integer (0 or negative) to move backward from the end of the file. A positive offset from the end would move beyond the file's actual content.
ImportantThe
whenceargument inF.seek(offset, whence)can only take the integer values 0, 1, or 2. Any other integer value will result in anOSErrororValueError.Now, let's examine the given statements based on these rules: …
- The
- CBSE 2023Set 91/11 markMCQQ.Which of the following mode keeps the file offset position at the end of the file?(a) r+(b) r(c) w(d) a
›Reveal solutionSolution
Mode a (append) keeps the file offset position at the end of the file, ensuring all writes happen after existing content.
When working with files in programming, the mode you choose determines not just whether you can read or write, but also where the file pointer starts and how the existing content is treated. Understanding these distinctions is essential for handling data correctly.
The r mode opens a file for reading only. The file pointer sits at the beginning, ready to read from the start. You cannot write in this mode, and if the file doesn't exist, you'll get an error. It's purely for consumption of existing data.
The r+ mode opens a file for both reading and writing. The file pointer again starts at the beginning. This means if you write immediately, you'll overwrite existing content from the start unless you explicitly move the pointer. The file must already exist, or the operation fails. It's a two-way mode but begins at the top.
The w mode opens a file for writing. Here's the crucial behavior: it truncates the file, meaning any existing content is wiped out the moment you open it. The file pointer is at the beginning of what is now an empty (or newly created) file. If the file didn't exist, it gets created. This mode is destructive by design. …
- CBSE 2023Set 91/11 markMCQQ.The syntax of seek() is: file_object.seek(offset[,reference_point]) What is the default value of reference_point?(a) 0(b) 1(c) 2(d) 3
›Reveal solutionSolution
The
seek()method changes the file object's current position. Itsreference_pointargument, which specifies the starting point for the offset, defaults to 0 — the beginning of the file. Correct option: (a).When you work with files, the operating system tracks your current position within the file — the "file pointer". The
seek()method lets you move this pointer manually. Its syntax isfile_object.seek(offset[, reference_point]), whereoffsetis the number of bytes to move andreference_pointis the position the offset is measured from.There are three standard reference points:
reference_point Measured from Note 0Beginning of the file Default; offset must be zero or positive 1Current file position Offset may be positive or negative 2End of the file Offset is usually zero or negative Because moving to an absolute position from the start of a file is by far the most common need,
seek()makes0the default. Sof.seek(7)is exactly the same asf.seek(7, 0)— both move the pointer 7 bytes from the beginning. … - CBSE 2023Set 91/41 markMCQQ.Which of the following modes in Python creates a new file, if file does not exist and overwrites the content, if the file exists ?(a) r+(b) r(c) w(d) a
›Reveal solutionSolution
The
'w'(write) mode in Python creates a new file if it doesn't exist and overwrites all existing content if the file already does.When working with files in Python, we often need to specify how we intend to interact with the file. This is done through what are called "modes" when opening a file. These modes dictate whether you want to read from the file, write to it, append new content, or a combination of these actions, and also define how the system should behave if the file doesn't exist or already contains data. Understanding these modes is fundamental to effective file handling.
Let's look at the common file modes:
-
'r' (Read Mode):
This is the default mode. When you open a file in read mode, you can only read its contents. You cannot modify or add new data.
Watch outIf the file you are trying to open in
'r'mode does not exist, Python will raise aFileNotFoundError. It will never create a new file in this mode. -
'r+' (Read and Write Mode):
This mode allows you to both read from and write to a file. The file pointer is initially at the beginning of the file.
ImportantSimilar to
'r'mode, if the file does not exist when opened in'r+'mode, Python will raise aFileNotFoundError. It does not create a new file. If the file exists, writing will occur from the current position of the file pointer, potentially overwriting existing content from that point onwards. -
'w' (Write Mode):
This mode is specifically for writing data to a file. It has a very distinct behavior regarding file existence:
- If the file does not exist, Python will create a new, empty file with the specified name. …
-
- CBSE 2023Set 91/41 markMCQQ.The correct syntax of tell() is :(a) tell.file_object()(b) file_object.tell()(c) tell.file_object(1)(d) file_object.tell(1)
›Reveal solutionSolution
In Python file handling, the
tell()method is called on a file object using dot notation, with no arguments — the correct syntax isfile_object.tell().When you work with files in Python, you are essentially moving a cursor through a stream of data. Every time you read or write, that cursor advances. The
tell()method is the tool that tells you exactly where that cursor is at any moment — it returns the current position (as an integer representing bytes from the beginning of the file).The syntax follows the standard object-oriented pattern in Python. A file object — created by
open()— has methods attached to it. You access those methods by writing the object's name, a dot, and then the method name. Sofile_object.tell()is the correct form. No argument is needed inside the parentheses becausetell()simply reports the current position; it does not change it.NoteThe position returned by
tell()is measured in bytes, not characters. For text files, this distinction matters when the file uses multi-byte encodings like UTF-8 — but for most exam purposes, you can treat it as the cursor's offset from the start.Now look at the options given:
- (a)
tell.file_object()— This is wrong because it treatstellas if it were the object andfile_objectas a method. In Python, the object comes first, then the dot, then the method. - (b)
file_object.tell()— This is correct. The file object is the thing that knows its position, andtell()is the method that asks it. …
- (a)
- CBSE 2023Set 91/41 markMCQQ.Q. 17 and 18 are Assertion (A) and Reasoning (R) based questions. Mark the correct choice as(a) Both (A) and (R) are true and (R) is the correct explanation for (A).(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).(c) (A) is true but (R) is false.(d) (A) is false but (R) is true. Assertion (A) : readlines() reads all the lines from a text file and returns the lines along with newline as a list of strings. Reasoning (R) : readline() can read the entire text file line by line without using any looping statements.
›Reveal solutionSolution
The
readlines()method reads all lines into a list, whilereadline()reads one line at a time, requiring a loop to process an entire file.When working with text files in Python, a common task is to read their contents. Python provides several methods for this, each suited for different scenarios. Understanding the nuances of these methods, particularly
readlines()andreadline(), is crucial for efficient and correct file handling. These methods allow us to access the data stored in a file, whether we need it all at once or line by line.The
readlines()method is designed for situations where you need to load the entire content of a text file into memory as a collection of individual lines. When you callreadlines()on an open file object, it performs the following actions:- It reads every single line from the current position in the file until the end of the file is reached.
- It collects these lines into a list.
- Each element in this list is a string, representing one line from the file.
- Crucially, each of these string elements retains the newline character (
\n) at its end, which marks the termination of a line in the text file.
NoteThe newline character (
\n) is an invisible character that signifies the end of a line and causes the cursor to move to the beginning of the next line. Whenreadlines()returns a list of strings, these\ncharacters are included in the strings, unless they are explicitly removed (e.g., usingstrip()).In contrast, the
readline()method operates differently. Its purpose is to read a file one line at a time, which is particularly useful when dealing with very large files that might not fit entirely into memory, or when you need to process each line individually before moving to the next.- When
readline()is called, it reads only the next single line from the file. - It returns this line as a single string.
- Similar to
readlines(), this string also includes the newline character (\n) at its end, if present in the file. - If
readline()is called again, it reads the subsequent line. This sequential reading continues until the end of the file. When the end of the file is reached, subsequent calls toreadline()will return an empty string ('').
ImportantTo read the entire text file line by line using
readline(), you must employ a looping construct, such as awhileloop or aforloop (though aforloop directly over the file object is often more Pythonic for line-by-line iteration). Without a loop,readline()will only ever read the first line (or the next single line if called multiple times manually).Now, let's evaluate the given Assertion and Reasoning: …
- CBSE 2019Set 91/41 markQ.Write a statement in Python to open a text file WRITEUP.TXT so that new content can be written in it.(OR)Write a statement in Python to open a text file README.TXT so that existing content can be read from it.
›Reveal solutionSolution
Part (a): open for writing with
open("WRITEUP.TXT", "w").Part (b): open for reading with
open("README.TXT", "r").Part (a)
To write new content into a text file you use write mode,
"w". If the file does not exist Python creates it; if it does exist, its contents are truncated (erased) before writing begins.f = open("WRITEUP.TXT", "w") ``` …
🎓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.