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?"