File Handling in C

Lesson 20 of 20

Open a file, write to it, read it back and close it — the full fopen, fprintf, fgets and fclose lifecycle.

The big picture

Data that outlives the program

Files are how a program's work survives after it exits — fopen opens the door, fclose closes it.

FILE is a handle

fopen returns a FILE pointer — your ticket for every read and write that follows.

Modes matter

"r" reads an existing file, "w" creates or erases, "a" appends at the end.

Check for NULL

fopen fails on missing files or bad paths and returns NULL — always test before writing.

Always fclose

fclose flushes buffered bytes to disk and releases the file — forget it and you may lose data.