0
0
Cprogramming~5 mins

Opening and closing files - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Opening and closing files
O(n)
Understanding Time Complexity

When we open and close files in C, we want to know how the time it takes changes as we do more operations.

We ask: How does the time grow when opening and closing files multiple times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <stdio.h>

int main() {
    FILE *file;
    int n = 1000;
    for (int i = 0; i < n; i++) {
        file = fopen("data.txt", "r");
        if (file != NULL) {
            fclose(file);
        }
    }
    return 0;
}
    

This code opens and closes the same file n times in a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Opening and closing the file inside the loop.
  • How many times: Exactly n times, once per loop iteration.
How Execution Grows With Input

Each time we increase n, the number of open-close actions grows the same amount.

Input Size (n)Approx. Operations
1010 open-close pairs
100100 open-close pairs
10001000 open-close pairs

Pattern observation: The total work grows directly with n. Double n, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as you increase the number of times you open and close the file.

Common Mistake

[X] Wrong: "Opening and closing a file is instant, so it doesn't affect time much."

[OK] Correct: Each open and close takes some time, so doing it many times adds up and grows with n.

Interview Connect

Understanding how repeated file operations add up helps you explain performance in real programs and shows you think about efficiency clearly.

Self-Check

"What if we opened the file once before the loop and closed it after? How would the time complexity change?"