Practice Questions — File Handling (ifstream, ofstream, fstream)
← Back to NotesTopic-Specific Questions
Question 1
Easy
What does this code write to output.txt?
ofstream file("output.txt");
file << "Hello" << endl;
file << "World" << endl;
file.close();endl writes a newline and flushes the buffer.
The file contains two lines:
HelloWorldQuestion 2
Easy
What is the output?
ofstream out("test.txt");
out << "Line 1" << endl;
out.close();
ofstream out2("test.txt");
out2 << "Line 2" << endl;
out2.close();
ifstream in("test.txt");
string line;
while (getline(in, line)) cout << line << endl;
in.close();Default ofstream mode is ios::out which truncates the file.
Line 2Question 3
Easy
What is the output?
ofstream out("test.txt");
out << "Line 1" << endl;
out.close();
ofstream out2("test.txt", ios::app);
out2 << "Line 2" << endl;
out2.close();
ifstream in("test.txt");
string line;
while (getline(in, line)) cout << line << endl;
in.close();ios::app means append -- do not truncate.
Line 1Line 2Question 4
Easy
What is the output?
ofstream out("nums.txt");
out << "10 20 30" << endl;
out.close();
ifstream in("nums.txt");
int a, b, c;
in >> a >> b >> c;
cout << a + b + c;
in.close();>> reads whitespace-separated values.
60Question 5
Medium
What is the output?
ofstream out("test.txt");
out << "ABCDEFGHIJ";
out.close();
ifstream in("test.txt");
in.seekg(5);
char ch;
in.get(ch);
cout << ch << " " << in.tellg();seekg(5) moves to the 6th byte (0-indexed).
F 6Question 6
Medium
What is the output?
ifstream file("nonexistent.txt");
cout << file.is_open() << " ";
cout << file.good() << " ";
cout << file.fail();The file does not exist.
0 0 1Question 7
Medium
What is the output?
ofstream out("data.txt");
out << "Arjun Kumar 85";
out.close();
ifstream in("data.txt");
string word;
int count = 0;
while (in >> word) count++;
cout << count;>> reads whitespace-separated tokens.
3Question 8
Medium
What is the output?
ofstream out("data.txt");
out << "Arjun Kumar 85";
out.close();
ifstream in("data.txt");
string line;
int count = 0;
while (getline(in, line)) count++;
cout << count;getline reads the entire line including spaces.
1Question 9
Hard
What is the output?
struct Data { int x; int y; };
Data d1 = {10, 20};
ofstream out("data.bin", ios::binary);
out.write(reinterpret_cast<char*>(&d1), sizeof(Data));
out.close();
ifstream in("data.bin", ios::binary);
Data d2;
in.read(reinterpret_cast<char*>(&d2), sizeof(Data));
cout << d2.x << " " << d2.y;Binary write stores the exact bytes of the struct.
10 20Question 10
Hard
What is the output?
ofstream out("test.txt");
out << "Hello World";
out.close();
ifstream in("test.txt", ios::binary);
in.seekg(0, ios::end);
cout << in.tellg();seekg(0, ios::end) moves to the end of the file. tellg() returns the position.
11Question 11
Medium
What is the difference between ios::app and ios::ate?
Both position at the end, but they differ in what happens during writes.
ios::app (append) always writes to the end of the file, regardless of any seekp calls. Every write operation is guaranteed to append. ios::ate (at end) positions the cursor at the end when the file is opened, but you can seekp to any position and write there. ios::app is safer for log files where you always want to append.Question 12
Hard
Why should you never use while(!file.eof()) as a loop condition?
Think about when the eof flag is actually set.
The
eof() flag is set only after a read operation fails, not when the last successful read reaches the end of data. Using while(!eof()) causes the loop to execute one extra time after the last valid read: the read fails, the old data is processed again, and then eof is detected. The correct pattern is while(getline(file, line)) or while(file >> var), where the read result is the condition.Mixed & Application Questions
Question 1
Easy
What is the output?
ofstream file("greet.txt");
file << "Hello ";
file << "World";
file.close();
ifstream in("greet.txt");
string content;
getline(in, content);
cout << content.length();There is no endl between Hello and World.
11Question 2
Easy
What happens when you run this code?
ofstream file;
file << "Hello";
file.close();The file was never opened.
Nothing is written anywhere. The stream is in a failed state because no file was opened. The
<< operation silently fails.Question 3
Medium
What is the output?
ofstream out("test.txt");
for (int i = 1; i <= 5; i++)
out << i << " ";
out.close();
ifstream in("test.txt");
int sum = 0, num;
while (in >> num) sum += num;
cout << sum;The file contains "1 2 3 4 5 ".
15Question 4
Medium
What is the output?
ofstream out("test.txt");
out << "Name: Arjun" << endl;
out << "Age: 20" << endl;
out.close();
ifstream in("test.txt");
string line;
int lineCount = 0;
while (getline(in, line)) {
if (line.find("Age") != string::npos)
cout << line;
lineCount++;
}
cout << " (" << lineCount << " lines)";find() returns string::npos if the substring is not found.
Age: 20 (2 lines)Question 5
Medium
What is the output?
struct Point { int x; int y; };
Point p1 = {3, 7};
ofstream out("point.bin", ios::binary);
out.write(reinterpret_cast<char*>(&p1), sizeof(Point));
out.close();
ifstream in("point.bin", ios::binary);
in.seekg(0, ios::end);
cout << in.tellg();sizeof(Point) is typically sizeof(int) + sizeof(int).
8Question 6
Hard
What is the output?
ofstream out("seq.txt");
for (int i = 0; i < 3; i++)
out << i << endl;
out.close();
ifstream in("seq.txt");
int val;
while (!in.eof()) {
in >> val;
cout << val << " ";
}This uses the problematic while(!eof()) pattern.
0 1 2 2Question 7
Easy
What is the difference between ifstream, ofstream, and fstream?
Think about read-only, write-only, and read-write.
ifstream opens files for reading only (input). ofstream opens files for writing only (output, truncates by default). fstream can do both reading and writing, but you must specify the mode explicitly (e.g., ios::in | ios::out). Use the most restrictive type that meets your needs.Question 8
Medium
What is reinterpret_cast used for in binary file I/O?
write() and read() expect a char* pointer.
write() and read() take a char* (pointer to bytes) and a byte count. reinterpret_cast<char*> converts a pointer to any type (struct, int, etc.) into a char*, telling the compiler to treat the memory as raw bytes. This allows writing the raw memory representation of any object to a file.Question 9
Hard
Why is random access possible in binary files with fixed-size records but not in text files with variable-length lines?
Think about how you calculate the byte position of record N.
In binary files with fixed-size records (e.g., all records are sizeof(Student) = 64 bytes), the byte offset of record N is exactly
N * sizeof(Student). You can seekg to that position in O(1). In text files, each line can have a different length ("Arjun" is 5 chars, "Raghunath" is 9 chars), so you cannot compute the byte offset of line N without reading all preceding lines. Text files require sequential access.Multiple Choice Questions
MCQ 1
Which header provides ifstream, ofstream, and fstream?
Answer: B
B is correct. The
B is correct. The
<fstream> header provides all file stream classes: ifstream, ofstream, and fstream.MCQ 2
What is the default mode for ofstream?
Answer: B
B is correct. ofstream defaults to
B is correct. ofstream defaults to
ios::out, which truncates the file if it exists. Use ios::app to append instead.MCQ 3
Which function reads an entire line including spaces from a file?
Answer: C
C is correct.
C is correct.
getline(file, line) reads until the newline, including spaces. The >> operator stops at whitespace.MCQ 4
What does file.is_open() return if the file was not found?
Answer: B
B is correct.
B is correct.
is_open() returns false if the file could not be opened for any reason (not found, permission denied, etc.).MCQ 5
What does ios::app mode do?
Answer: C
C is correct.
C is correct.
ios::app ensures every write goes to the end of the file, preserving existing content.MCQ 6
What does seekg(0, ios::end) followed by tellg() give you?
Answer: C
C is correct. Seeking to the end and calling
C is correct. Seeking to the end and calling
tellg() returns the byte position at the end, which equals the file size.MCQ 7
What does reinterpret_cast(&obj) do?
Answer: B
B is correct.
B is correct.
reinterpret_cast<char*> tells the compiler to treat the memory at that address as raw bytes (char*). This is required for write() and read() which operate on byte buffers.MCQ 8
What is the correct way to read integers from a file until end?
Answer: B
B is correct.
B is correct.
file >> num returns the stream, which converts to false when the read fails. This is the idiomatic and correct pattern. Options A and C process the last value twice.MCQ 9
What is the difference between seekg and seekp?
Answer: B
B is correct.
B is correct.
seekg (seek get) positions the read pointer. seekp (seek put) positions the write pointer. In an fstream, both may be needed.MCQ 10
Why must you use ios::binary when using write() and read() for struct I/O?
Answer: B
B is correct. In text mode, the runtime may translate \n to \r\n (Windows) or vice versa. If the struct's raw bytes happen to contain 0x0A (\n byte), this translation corrupts the data. Binary mode performs no translation.
B is correct. In text mode, the runtime may translate \n to \r\n (Windows) or vice versa. If the struct's raw bytes happen to contain 0x0A (\n byte), this translation corrupts the data. Binary mode performs no translation.
MCQ 11
How do you calculate the byte position of the Nth record in a binary file with fixed-size records?
Answer: B
B is correct. With 0-based indexing, record N starts at byte position
B is correct. With 0-based indexing, record N starts at byte position
N * sizeof(Record). Use seekg with this value for O(1) random access.MCQ 12
What happens if you open a file with ofstream (default mode) that already contains data?
Answer: B
B is correct. The default mode for ofstream is
B is correct. The default mode for ofstream is
ios::out, which implies ios::trunc. The file is truncated to zero length before any new data is written.MCQ 13
How do you combine file modes in C++?
Answer: C
C is correct. File modes are combined using the bitwise OR operator (
C is correct. File modes are combined using the bitwise OR operator (
|). Example: ios::in | ios::out | ios::binary.MCQ 14
What does file.close() do?
Answer: B
B is correct.
B is correct.
close() flushes any buffered data to disk and releases the OS file handle. The file remains on disk.Coding Challenges
Challenge 1: Word Frequency Counter from File
EasyRead a text file word by word and count the frequency of each word. Print the words and their counts in alphabetical order. Use a map to store counts.
Sample Input
File content: "the cat sat on the mat the cat"
Sample Output
cat: 2
mat: 1
on: 1
sat: 1
the: 3
Use ifstream with >> to read words. Use map<string, int> for counting.
#include <iostream>
#include <fstream>
#include <map>
#include <string>
using namespace std;
int main() {
ofstream out("text.txt");
out << "the cat sat on the mat the cat";
out.close();
ifstream in("text.txt");
map<string, int> freq;
string word;
while (in >> word) freq[word]++;
in.close();
for (auto& [w, c] : freq)
cout << w << ": " << c << endl;
return 0;
}Challenge 2: Student Marks CSV Parser and Topper Finder
MediumWrite a CSV file with student name, maths, physics, chemistry marks. Read the CSV, calculate total marks for each student, and find the topper. Use stringstream to parse comma-separated values.
Sample Input
Arjun,85,90,78
Priya,92,88,95
Kiran,78,82,80
Sample Output
Arjun: Total=253
Priya: Total=275
Kiran: Total=240
Topper: Priya (275)
Use getline for reading lines, stringstream for parsing. Do not hardcode the number of students.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ofstream out("marks.csv");
out << "Arjun,85,90,78" << endl;
out << "Priya,92,88,95" << endl;
out << "Kiran,78,82,80" << endl;
out.close();
ifstream in("marks.csv");
string line, topperName;
int topperTotal = 0;
while (getline(in, line)) {
stringstream ss(line);
string name, token;
getline(ss, name, ',');
int total = 0;
while (getline(ss, token, ','))
total += stoi(token);
cout << name << ": Total=" << total << endl;
if (total > topperTotal) {
topperTotal = total;
topperName = name;
}
}
cout << "Topper: " << topperName << " (" << topperTotal << ")" << endl;
in.close();
return 0;
}Challenge 3: Binary Student Database with Search and Update
HardImplement a student database using binary file I/O. Support: (1) Add student record, (2) Display all records, (3) Search by roll number, (4) Update marks by roll number. Use seekg/seekp for in-place updates.
Sample Input
Add {101, Arjun, 85}, {102, Priya, 78}. Update roll 102 marks to 95. Display all.
Sample Output
101: Arjun, Marks: 85
102: Priya, Marks: 95
Use fixed-size struct with char array for name (not string). Use seekg/seekp for O(1) updates.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct Student {
int rollNo;
char name[30];
double marks;
};
void addStudent(const string& fname, int roll, const char* name, double marks) {
Student s;
s.rollNo = roll;
strcpy(s.name, name);
s.marks = marks;
ofstream file(fname, ios::binary | ios::app);
file.write(reinterpret_cast<char*>(&s), sizeof(Student));
file.close();
}
void updateMarks(const string& fname, int roll, double newMarks) {
fstream file(fname, ios::in | ios::out | ios::binary);
Student s;
while (file.read(reinterpret_cast<char*>(&s), sizeof(Student))) {
if (s.rollNo == roll) {
s.marks = newMarks;
file.seekp(-static_cast<int>(sizeof(Student)), ios::cur);
file.write(reinterpret_cast<char*>(&s), sizeof(Student));
break;
}
}
file.close();
}
void displayAll(const string& fname) {
ifstream file(fname, ios::binary);
Student s;
while (file.read(reinterpret_cast<char*>(&s), sizeof(Student)))
cout << s.rollNo << ": " << s.name << ", Marks: " << s.marks << endl;
file.close();
}
int main() {
string fname = "students.dat";
ofstream clear(fname, ios::trunc); clear.close();
addStudent(fname, 101, "Arjun", 85);
addStudent(fname, 102, "Priya", 78);
updateMarks(fname, 102, 95);
displayAll(fname);
return 0;
}Challenge 4: Config File Parser with Default Values
MediumWrite a config file parser that reads key=value pairs, skips comment lines (starting with #) and empty lines. Provide a get method that returns a default value if the key is not found.
Sample Input
# Config file
host=localhost
port=3306
debug=true
Sample Output
host = localhost
port = 3306
debug = true
timeout = 30 (default)
Use map<string, string> for storage. Support # comments and empty lines. Provide a get(key, default) method.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
using namespace std;
class Config {
map<string, string> data;
public:
void load(const string& filename) {
ifstream file(filename);
string line;
while (getline(file, line)) {
if (line.empty() || line[0] == '#') continue;
size_t pos = line.find('=');
if (pos != string::npos)
data[line.substr(0, pos)] = line.substr(pos + 1);
}
file.close();
}
string get(const string& key, const string& defaultVal = "") {
auto it = data.find(key);
return it != data.end() ? it->second : defaultVal;
}
void display() {
for (auto& [k, v] : data) cout << k << " = " << v << endl;
}
};
int main() {
ofstream out("app.conf");
out << "# Config file" << endl;
out << "host=localhost" << endl;
out << "port=3306" << endl;
out << "debug=true" << endl;
out.close();
Config config;
config.load("app.conf");
config.display();
cout << "timeout = " << config.get("timeout", "30") << " (default)" << endl;
return 0;
}Challenge 5: File-based Leaderboard System
HardCreate a leaderboard system that stores player names and scores in a text file. Support adding new scores, reading all scores, sorting by score (descending), and displaying the top N players. The file persists between program runs.
Sample Input
Add: Arjun 850, Priya 920, Kiran 780, Neha 920. Display top 3.
Sample Output
=== Top 3 ===
1. Neha: 920
2. Priya: 920
3. Arjun: 850
Read from file, sort in memory, display. Handle the case where the file does not exist.
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct Player {
string name;
int score;
};
void addScore(const string& fname, const string& name, int score) {
ofstream file(fname, ios::app);
file << name << " " << score << endl;
file.close();
}
vector<Player> loadScores(const string& fname) {
vector<Player> players;
ifstream file(fname);
string name;
int score;
while (file >> name >> score)
players.push_back({name, score});
file.close();
return players;
}
void showTop(const string& fname, int n) {
auto players = loadScores(fname);
sort(players.begin(), players.end(),
[](const Player& a, const Player& b) { return a.score > b.score; });
cout << "=== Top " << n << " ===" << endl;
for (int i = 0; i < min(n, (int)players.size()); i++)
cout << i + 1 << ". " << players[i].name << ": " << players[i].score << endl;
}
int main() {
string fname = "leaderboard.txt";
ofstream clear(fname, ios::trunc); clear.close();
addScore(fname, "Arjun", 850);
addScore(fname, "Priya", 920);
addScore(fname, "Kiran", 780);
addScore(fname, "Neha", 920);
showTop(fname, 3);
return 0;
}Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn C++ with a live mentor?
Explore our C++ Masterclass