The FILE * stream API in <stdio.h> reads and writes files. Always check return values and close files with fclose.
Open, read, close
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) { /* error */ }
fprintf(fp, "line\n");
fclose(fp);
Modes
"r"— read"w"— write (truncate)"a"— append
In the playground, file I/O may be limited—patterns still apply locally.
Important interview questions and answers
- Q: fopen failure?
A: Returns NULL—check before use; errno may hold details. - Q: fflush vs fclose?
A:fflushpushes buffered data;fcloseflushes and releases the stream.
Self-check
- Which function writes formatted text to a file?
- Why check fopen return value?
Pitfall: Forgetting fclose leaks file descriptors—in long-running servers this exhausts OS limits.
Interview prep
- fopen failure?
Returns NULL—check before use; inspect
errnofor details on POSIX systems.