File output using ofstream in C++ - Time & Space Complexity
When writing data to a file using ofstream, it's important to know how the time taken grows as the amount of data increases.
We want to understand how the program's running time changes when we write more lines to the file.
Analyze the time complexity of the following code snippet.
#include <fstream>
#include <string>
void writeToFile(int n) {
std::ofstream file("output.txt");
for (int i = 0; i < n; ++i) {
file << "Line " << i << "\n";
}
file.close();
}
This code opens a file and writes n lines, each with a line number, then closes the file.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing a line to the file inside the loop.
- How many times: The loop runs n times, so the write operation repeats n times.
Each additional line means one more write operation, so the total work grows steadily as n grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes |
| 100 | 100 writes |
| 1000 | 1000 writes |
Pattern observation: The number of operations grows directly in proportion to n.
Time Complexity: O(n)
This means the time to write grows linearly with the number of lines you write.
[X] Wrong: "Writing to a file is instant and does not depend on how many lines we write."
[OK] Correct: Each write takes time, so more lines mean more time. The program does more work as n grows.
Understanding how file writing scales helps you reason about program speed and resource use, a useful skill in many coding tasks.
"What if we buffered multiple lines before writing to the file? How would the time complexity change?"