GCGY Beta v1.0.1
GrowCodeEngineering
← Back to Hub
Back to Topics
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
Continue Path
Challenge: Write main() to verify file handling pointer syntax.
C Level 8: File Stream Handling
1
2
3
4
5
6
7
8
9
10
11
12
13
No test case execution results available yet. Click "Run Code" to evaluate your solution.