Error handling in files in C - Time & Space Complexity
When working with files in C, error handling ensures the program reacts properly if something goes wrong.
We want to see how checking for errors affects how long the program takes to run.
Analyze the time complexity of the following code snippet.
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
char buffer[100];
while (fgets(buffer, sizeof(buffer), file)) {
// process buffer
}
fclose(file);
This code opens a file, checks for errors, reads lines one by one, and then closes the file.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading each line from the file inside the while loop.
- How many times: Once for each line until the end of the file.
As the file gets bigger, the number of lines grows, so the loop runs more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 lines | About 10 reads |
| 100 lines | About 100 reads |
| 1000 lines | About 1000 reads |
Pattern observation: The time grows directly with the number of lines in the file.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of lines read from the file.
[X] Wrong: "Checking for errors like fopen failure makes the program slower for big files."
[OK] Correct: The error check happens only once before reading, so it does not grow with file size and does not slow down the reading loop.
Understanding how error checks fit into program speed shows you can write safe code without guessing about performance.
"What if we added a nested loop to process each character in every line? How would the time complexity change?"
Practice
fopen return if it fails to open a file in C?Solution
Step 1: Understand
Thefopenbehaviorfopenfunction returns a pointer to a FILE object if successful.Step 2: Identify failure return value
Iffopenfails (e.g., file not found), it returnsNULLto indicate error.Final Answer:
NULL -> Option DQuick Check:
fopenfailure returns NULL [OK]
- Thinking fopen returns 0 on failure
- Confusing NULL with empty string
- Assuming fopen throws an error instead of returning NULL
Solution
Step 1: Recall fopen return value on failure
fopenreturnsNULLif it fails to open a file.Step 2: Write correct check for success
To check if opened successfully, compare the file pointer usingfile != NULL.Final Answer:
if (file != NULL) -> Option AQuick Check:
Check file pointer against NULL for success [OK]
- Using 0 or -1 instead of NULL for pointer check
- Checking if file == NULL to confirm success
- Confusing integer and pointer comparisons
#include <stdio.h>
int main() {
FILE *fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
printf("File open failed\n");
} else {
printf("File opened\n");
fclose(fp);
}
return 0;
}Solution
Step 1: fopen tries to open a non-existing file
The file "nonexistent.txt" does not exist, sofopenreturnsNULL.Step 2: Check the if condition and output
Sincefp == NULLis true, the program prints "File open failed".Final Answer:
File open failed -> Option BQuick Check:
fopen fails, prints failure message [OK]
- Assuming file opens successfully
- Ignoring the NULL check
- Expecting compilation error due to fopen
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("Error opening file\n");
}
fclose(fp);
return 0;
}Solution
Step 1: Analyze fopen and NULL check
The code checks iffp == NULLand prints error if true.Step 2: Check fclose usage
Even iffp == NULL, the code callsfclose(fp), which is invalid and causes undefined behavior.Final Answer:
Calling fclose even if fopen failed -> Option AQuick Check:
Only fclose valid file pointers, not NULL [OK]
- Calling fclose on NULL pointer
- Not checking fopen return before fclose
- Assuming fclose always succeeds without check
Solution
Step 1: Check fopen return value
The correct code checks iffopenreturnsNULLand handles error withperrorand exit.Step 2: Check fprintf return value and fclose return value
The correct code also checks iffprintffails (returns negative) and iffclosefails (returns non-zero), handling errors properly.Final Answer:
The code that checks fopen, fprintf, and fclose -> Option CQuick Check:
Check fopen, fprintf, fclose return values for safe file handling [OK]
- Not checking fopen return before writing
- Using wrong mode for writing
- Ignoring fclose errors
- Writing without checking fprintf success
Ready to prove it?
Pass the test and this pattern moves unknown
