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?"
Practice
fopen in C?Solution
Step 1: Understand fopen modes
The mode "w" in fopen means open for writing. If the file exists, it will be overwritten. If it doesn't exist, it will be created.Step 2: Compare with other modes
Other modes like "r" are for reading, "a" for appending, and "wb" for binary write. "w" specifically means write with overwrite or create.Final Answer:
Open a file for writing, creating it if it doesn't exist, or overwriting if it does. -> Option AQuick Check:
fopen mode "w" = write with overwrite [OK]
- Confusing "w" with "a" (append mode)
- Thinking "w" opens file for reading
- Assuming "w" preserves existing content
Solution
Step 1: Identify correct function and mode
In C, to open a file for writing, use fopen with mode "w". The function is fopen, not open.Step 2: Check each option
FILE *fp = fopen("data.txt", "r"); uses mode "r" (read), not writing. FILE *fp = fopen("data.txt", "a"); uses "a" (append). FILE *fp = open("data.txt", "w"); uses open, which is not standard C file open function.Final Answer:
FILE *fp = fopen("data.txt", "w"); -> Option AQuick Check:
Use fopen with "w" to write [OK]
- Using open() instead of fopen()
- Using wrong mode like "r" or "a"
- Forgetting to use double quotes around filename
FILE *fp = fopen("output.txt", "w");
fprintf(fp, "Hello %s!", "World");
fclose(fp);Solution
Step 1: Understand fprintf usage
fprintf writes formatted text to the file. The format string "Hello %s!" expects a string argument, which is "World" here.Step 2: Determine file content
The file will contain the formatted string with %s replaced by "World", so the file content is "Hello World!".Final Answer:
Hello World! -> Option CQuick Check:
fprintf formats string correctly [OK]
- Thinking %s prints literally
- Forgetting to pass argument for %s
- Assuming fprintf prints to console
FILE *fp;
fp = fopen("test.txt", "w");
fprintf(fp, "Test");Solution
Step 1: Check file opening and writing
The file is opened correctly with fopen and mode "w". fprintf syntax is correct to write "Test".Step 2: Check for missing file closure
The code does not call fclose(fp), which is necessary to close the file and flush buffers properly.Final Answer:
Missing fclose(fp) to close the file -> Option DQuick Check:
Always close files with fclose [OK]
- Forgetting fclose causes data loss
- Confusing fopen modes
- Thinking fprintf needs format specifier always
1) FILE *fp = fopen("log.txt", "w");
fprintf(fp, "Line 1\n");
fprintf(fp, "Line 2\n");
fclose(fp);
2) FILE *fp = fopen("log.txt", "r");
fprintf(fp, "Line 1\n");
fclose(fp);
3) FILE *fp = fopen("log.txt", "w");
fprintf(fp, "Line 1\nLine 2\n");
// missing fclose
4) FILE *fp = fopen("log.txt", "a");
fprintf(fp, "Line 1\n");
fclose(fp);Solution
Step 1: Analyze each option's correctness
Option 1 opens file with "w" (write), writes two lines separately, and closes file properly. This is correct.Step 2: Check other options
Option 2 opens with "r" (read), so writing causes error. Option 3 writes lines but misses fclose, risking data loss. Option 4 opens with "a" (append), writes only one line, but the goal is multiple lines.Final Answer:
Option 1 only -> Option BQuick Check:
"w" + multiple fprintf + fclose [OK]
- Using "r" mode when writing
- Forgetting fclose after writing
- Not understanding difference between "w" and "a"
Ready to prove it?
Pass the test and this pattern moves unknown
