File modes in C - Time & Space Complexity
When working with files in C, the mode you choose affects how the program reads or writes data.
We want to understand how the time to open and process a file changes as the file size grows.
Analyze the time complexity of the following code snippet.
FILE *file = fopen("data.txt", "r");
char buffer[256];
while (fgets(buffer, sizeof(buffer), file)) {
// process the line
}
fclose(file);
This code opens a file in read mode and reads it line by line until the end.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading each line from the file using fgets.
- How many times: Once for every line in the file until the end.
As the file gets bigger, the program reads more lines, so it takes longer.
| Input Size (lines) | Approx. Operations (reads) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows directly with the number of lines in the file.
Time Complexity: O(n)
This means the time to read the file grows linearly with the number of lines.
[X] Wrong: "Opening a file is slow and depends on file size."
[OK] Correct: Opening a file is usually a quick operation; the time depends mostly on how much data you read or write, not just opening.
Understanding how file reading scales helps you write efficient programs and answer questions about handling large data files.
"What if we changed the mode from reading line by line to reading the entire file at once? How would the time complexity change?"