0
0
C++programming~5 mins

File output using ofstream in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: File output using ofstream
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each additional line means one more write operation, so the total work grows steadily as n grows.

Input Size (n)Approx. Operations
1010 writes
100100 writes
10001000 writes

Pattern observation: The number of operations grows directly in proportion to n.

Final Time Complexity

Time Complexity: O(n)

This means the time to write grows linearly with the number of lines you write.

Common Mistake

[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.

Interview Connect

Understanding how file writing scales helps you reason about program speed and resource use, a useful skill in many coding tasks.

Self-Check

"What if we buffered multiple lines before writing to the file? How would the time complexity change?"