Writing to files in C - Time & Space Complexity
When writing data to files in C, it's important to know how the time it takes grows as the amount of data grows.
We want to understand how the program's work changes when we write more data.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
void writeNumbersToFile(int n) {
FILE *file = fopen("numbers.txt", "w");
for (int i = 0; i < n; i++) {
fprintf(file, "%d\n", i);
}
fclose(file);
}
This code writes numbers from 0 up to n-1 into a file, one number per line.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that writes each number to the file.
- How many times: Exactly n times, once for each number.
Each time we increase n, the program writes more lines, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes |
| 100 | 100 writes |
| 1000 | 1000 writes |
Pattern observation: The number of writes grows in a straight line with n.
Time Complexity: O(n)
This means the time to write grows directly in proportion to how many numbers we write.
[X] Wrong: "Writing to a file is always constant time, no matter how much data."
[OK] Correct: Writing more data means more work; the program must handle each piece, so time grows with data size.
Understanding how file writing scales helps you explain program efficiency clearly and shows you can think about real-world program behavior.
"What if we buffered multiple numbers before writing to the file? How would the time complexity change?"