Reading and writing files in C++ - Time & Space Complexity
When reading or writing files, the time it takes depends on how much data we handle.
We want to know how the time grows as the file size gets bigger.
Analyze the time complexity of the following code snippet.
#include <fstream>
#include <string>
void copyFile(const std::string& input, const std::string& output) {
std::ifstream inFile(input);
std::ofstream outFile(output);
std::string line;
while (std::getline(inFile, line)) {
outFile << line << '\n';
}
}
This code reads a file line by line and writes each line to another file.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading each line from the input file and writing it to the output file.
- How many times: Once for every line in the file, repeating until the file ends.
As the file gets bigger, the number of lines grows, so the time to read and write grows too.
| Input Size (n lines) | Approx. Operations |
|---|---|
| 10 | About 10 reads and 10 writes |
| 100 | About 100 reads and 100 writes |
| 1000 | About 1000 reads and 1000 writes |
Pattern observation: The time grows roughly in direct proportion to the number of lines.
Time Complexity: O(n)
This means the time to read and write grows linearly with the number of lines in the file.
[X] Wrong: "Reading a file always takes constant time regardless of size."
[OK] Correct: The program reads each line one by one, so bigger files take more time.
Understanding how file size affects reading and writing time helps you explain performance in real programs.
"What if we read the file character by character instead of line by line? How would the time complexity change?"
Practice
ifstream in C++?Solution
Step 1: Understand the role of
ifstreamifstreamstands for input file stream, which is used to read data from files.Step 2: Differentiate from
ofstreamofstreamis used to write data to files, so it is not the correct answer here.Final Answer:
To read data from a file -> Option BQuick Check:
ifstream= read file [OK]
- Confusing ifstream with ofstream
- Thinking ifstream creates or deletes files
- Mixing input and output streams
data.txt for writing using ofstream?Solution
Step 1: Recognize correct
To open a file for writing, you create anofstreamsyntaxofstreamobject and pass the filename to its constructor.Step 2: Check other options for syntax errors
ifstream file("data.txt"); usesifstreamwhich is for reading, not writing. ofstream file.open("data.txt"); incorrectly callsopenas a constructor. file.open(ofstream, "data.txt"); has wrong parameter order and syntax.Final Answer:
ofstream file("data.txt"); -> Option DQuick Check:
Correctofstreamconstructor usage = ofstream file("data.txt"); [OK]
- Using ifstream instead of ofstream for writing
- Calling open() incorrectly
- Passing wrong arguments to open()
numbers.txt contains the numbers 10 and 20 on separate lines?
std::ifstream file("numbers.txt");
int a, b;
file >> a >> b;
std::cout << a + b << std::endl;
file.close();Solution
Step 1: Understand file reading with >> operator
The code reads two integers from the file into variablesaandb. Since the file has 10 and 20 on separate lines,a= 10 andb= 20.Step 2: Calculate the output
The code outputs the sum ofaandb, which is 10 + 20 = 30.Final Answer:
30 -> Option AQuick Check:
10 + 20 = 30 [OK]
- Thinking >> concatenates numbers as strings
- Forgetting to close the file
- Assuming output is the first number only
output.txt:
std::ofstream file;
file << "Hello";
file.open("output.txt");
file.close();Solution
Step 1: Check order of operations
The code tries to write to the file before opening it, which is incorrect because the file must be opened first.Step 2: Confirm other options
Missing semicolon after file.open() is wrong because semicolons are present. ofstream cannot write strings is false; ofstream can write strings. File should be closed before opening is incorrect; you cannot close before opening.Final Answer:
File is opened after writing to it -> Option CQuick Check:
Open file before writing [OK]
- Writing before opening the file
- Confusing order of open and close
- Assuming ofstream can't write strings
input.txt and write only the even numbers to even.txt. Which code snippet correctly implements this?Solution
Step 1: Check correct stream types and file opening
std::ifstream inFile("input.txt"); std::ofstream outFile("even.txt"); int num; while (inFile >> num) { if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close(); correctly usesifstreamto read andofstreamto write, opening files in constructors.Step 2: Verify reading loop and condition
std::ifstream inFile("input.txt"); std::ofstream outFile("even.txt"); int num; while (inFile >> num) { if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close(); useswhile (inFile >> num)which safely reads integers until EOF. It writes only even numbers (num % 2 == 0) to output.Step 3: Identify errors in other options
std::ofstream inFile("input.txt"); std::ifstream outFile("even.txt"); int num; while (inFile >> num) { if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close(); swaps stream types incorrectly. std::ifstream inFile; std::ofstream outFile; inFile.open("input.txt"); outFile.open("even.txt"); int num; while (inFile >> num) { if (num % 2 == 1) { outFile << num << '\n'; } } inFile.close(); outFile.close(); writes odd numbers, not even. std::ifstream inFile("input.txt"); std::ofstream outFile("even.txt"); int num; while (!inFile.eof()) { inFile >> num; if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close(); useswhile (!inFile.eof())which can cause reading errors.Final Answer:
Option A code snippet -> Option AQuick Check:
Correct streams + safe read loop + even check = std::ifstream inFile("input.txt"); std::ofstream outFile("even.txt"); int num; while (inFile >> num) { if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close(); [OK]
- Swapping ifstream and ofstream
- Using eof() in loop condition
- Writing odd numbers instead of even
Ready to prove it?
Pass the test and this pattern moves unknown
