0
0
C++programming~5 mins

Reading and writing files in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reading and writing files
O(n)
Understanding Time 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.

Scenario Under Consideration

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

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

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
10About 10 reads and 10 writes
100About 100 reads and 100 writes
1000About 1000 reads and 1000 writes

Pattern observation: The time grows roughly in direct proportion to the number of lines.

Final Time Complexity

Time Complexity: O(n)

This means the time to read and write grows linearly with the number of lines in the file.

Common Mistake

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

Interview Connect

Understanding how file size affects reading and writing time helps you explain performance in real programs.

Self-Check

"What if we read the file character by character instead of line by line? How would the time complexity change?"