Opening and closing files - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Opening and closing the file inside the loop.
- How many times: Exactly
ntimes, once per loop iteration.
Each time we increase n, the number of open-close actions grows the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 open-close pairs |
| 100 | 100 open-close pairs |
| 1000 | 1000 open-close pairs |
Pattern observation: The total work grows directly with n. Double n, double the work.
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.
[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.
Understanding how repeated file operations add up helps you explain performance in real programs and shows you think about efficiency clearly.
"What if we opened the file once before the loop and closed it after? How would the time complexity change?"