c / c-arrays-strings
20 mins
C Level 8: File Stream Handling
Why This Matters: Files allow C programs to read and write persistent data stored on disk across program runs.
## File Stream Handling in C
Disk file I/O is managed using file stream pointers (`FILE*`).
### Modes
- `"r"`: Read mode.
- `"w"`: Write mode (creates file or truncates existing).
- `"a"`: Append mode.
```c
FILE *fp = fopen("data.txt", "w");
if (fp != NULL) {
fprintf(fp, "Score: %d
", 100);
fclose(fp); // Flush buffer & close stream
}
```
MENTAL MODEL & MEMORY LAYOUT
[ Program RAM ] ──(fprintf)──► [ File Stream Buffer ] ──(fclose)──► [ Disk Storage (data.txt) ]
COMMON PITFALLS TO AVOID
- Forgetting to call `fclose(fp)` causing unwritten stream buffers to corrupt.
- Failing to check `if (fp == NULL)` before reading file pointers.
Safe File Stream Pattern
#include <stdio.h>
int main() {
FILE *fp = fopen("log.txt", "a");
if (fp != NULL) {
fputs("System event logged.\n", fp);
fclose(fp);
printf("Log complete.\n");
}
return 0;
}Appends text to log file stream and closes handle cleanly.
CONCEPT MASTERY CHECKPOINT
Why must you always call `fclose(fp)` after finishing file operations in C?
NEXT RECOMMENDED LESSON
C Level 9: Problem Solving & Algorithms
Challenge: Write main() to verify file handling pointer syntax.