File Handling in C
Reading from and writing to files — making your data outlive the program.
Opening a File
fopen() opens a file and returns a FILE pointer, used for all further operations on it. Common modes: "r" (read), "w" (write, overwrites existing content), "a" (append, adds to the end).
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) { /* handle error */ }
fprintf(fp, "Hello File!\n");
fclose(fp);Reading and Writing
fprintf()/fscanf() work like printf()/scanf() but read from or write to a file instead of the screen. fgets() reads a full line from a file safely, and fputs() writes a string to a file.
Always Close Your Files
fclose() must be called when you're done with a file — it saves any buffered data to disk and releases the file handle. Forgetting this can cause data loss (unsaved buffered writes) or hit the OS's limit on open files.
🌍 Real-World Use
A simple student record system that saves data between program runs, a log file that records errors over time, or a configuration file loaded at program startup — all use file handling to make data persistent.
💡 Pro Tip
Always check if fopen() returned NULL before using the file pointer — a missing file, wrong path, or permission issue will make fopen() fail silently return NULL, and skipping this check is a very common cause of crashes.
🧪 Quick Self-Test
Check what you just learned — no pressure, just practice.
1. Which file mode overwrites existing content?
2. Why must you call fclose() after working with a file?