Why is file handling important in programming?
Think about what happens to data when a program closes.
File handling lets programs save data permanently on disk. Without it, data would be lost when the program ends.
What will be the output of this C++ code snippet?
#include <iostream> #include <fstream> using namespace std; int main() { ofstream file("test.txt"); file << "Hello World"; file.close(); ifstream fileIn("test.txt"); string content; getline(fileIn, content); cout << content << endl; fileIn.close(); return 0; }
Look at what is written to the file and then read back.
The program writes "Hello World" to a file and then reads it back to print. So the output is "Hello World".
What error will this code produce when run?
#include <iostream> #include <fstream> using namespace std; int main() { ifstream file("missing.txt"); string line; getline(file, line); cout << line << endl; return 0; }
What happens if you try to read a file that is not there?
The program tries to open a file that does not exist. This causes a runtime error or the input stream fails, so reading fails.
Which option shows the correct way to open a file for writing in C++?
Remember how to create an output file stream object.
Option A correctly creates an ofstream object and opens the file "data.txt" for writing.
Given a file "numbers.txt" containing 5 lines, what will be the value of count after running this code?
#include <iostream> #include <fstream> using namespace std; int main() { ifstream file("numbers.txt"); string line; int count = 0; while (getline(file, line)) { count++; } cout << count << endl; return 0; }
Count how many lines are read by the loop.
The loop reads each line until the end of the file. Since the file has 5 lines, count will be 5.