File I/O in C

From the C cheat sheet · File I/O · verified Jul 2026

File I/O

fopen, fgets, fprintf, and fclose.

c
// Quick Reference
FILE *f = fopen("data.txt", "r");
if (!f) { perror("open"); }
fgets(buf, sizeof buf, f);
fclose(f);
💡 Always check fopen for NULL - the file may not exist or be permitted.
⚡ Every fopen needs a matching fclose, or you leak file descriptors and buffered writes.
📌 fgets/fprintf are for text; fread/fwrite handle raw binary blocks.
🟢 Use "b" mode (rb/wb) for binary files, especially for portability on Windows.
file-io
Back to the full C cheat sheet