File Handling in C
File handling in C lets your program read from and write to files on disk, so data survives after the program ends. The workflow is always the same three steps: open a file with fopen, read or write it, and close it with fclose. Everything goes through a FILE * — a pointer to a file stream.
Opening a file
fopen takes a filename and a mode, and returns a FILE *. If it fails (file missing, no permission), it returns NULL — always check:
FILE *fp = fopen("data.txt", "r"); /* "r" = open for reading */
if (fp == NULL) {
printf("Could not open file.\n");
return 1;
}
Common modes:
| Mode | Meaning |
|---|---|
"r" | read (file must exist) |
"w" | write (creates or erases existing) |
"a" | append (adds to the end) |
"r+" | read and write |
Add b (e.g. "rb") for binary files; text mode is the default.
Writing to a file
Use fprintf exactly like printf, but with the file pointer as the first argument:
#include <stdio.h>
int main(void) {
FILE *fp = fopen("notes.txt", "w"); /* create/overwrite */
if (fp == NULL) {
printf("Open failed.\n");
return 1;
}
fprintf(fp, "Hello from Jalgaon\n"); /* write a line */
fprintf(fp, "Line 2: %d\n", 42); /* formatting works too */
fclose(fp); /* ALWAYS close: flushes data and frees the handle */
return 0;
}
"w" mode erases any existing content, so use "a" if you want to keep adding.
Reading from a file
fgets reads one line at a time and is the safe choice for text. Loop until it returns NULL (end of file):
#include <stdio.h>
int main(void) {
FILE *fp = fopen("notes.txt", "r");
if (fp == NULL) {
printf("Open failed.\n");
return 1;
}
char line[256];
while (fgets(line, sizeof(line), fp) != NULL) { /* read line by line */
printf("%s", line); /* fgets keeps the newline, so no extra \n */
}
fclose(fp);
return 0;
}
Want to learn this properly?
Join the waitlist for C Programming — beginner-friendly, project-first classes in Jalgaon.
Explore C ProgrammingWhy fclose matters
Closing a file flushes any buffered data to disk and releases the operating system handle. Forgetting fclose can lose the last writes or leak resources. Close every file you open.
Appending instead of overwriting
When you want to keep a file's existing contents and add to the end — a log file, for example — open it in append mode "a":
#include <stdio.h>
int main(void) {
FILE *fp = fopen("log.txt", "a"); /* "a" preserves existing lines */
if (fp == NULL) {
return 1;
}
fprintf(fp, "New entry\n"); /* added at the end, old lines kept */
fclose(fp);
return 0;
}
Run this a few times and you'll see the file grow rather than reset — the key difference between "a" and "w".
Other useful functions
fscanf— formatted reading (likescanffrom a file). Use carefully;fgetsis safer for whole lines.fputc/fgetc— write/read a single character.feof/ferror— check end-of-file and error states.rewind— move the read/write position back to the start of the file.
Common mistakes
- Not checking
fopenforNULL— then using a bad pointer crashes the program. - Forgetting
fclose— buffered writes may never reach the disk. - Using
"w"when you meant"a"—"w"silently erases the file. - Reading past end of file without checking the return value of
fgets/fscanf. - Buffer too small for
fgets— long lines get split; size your buffer generously.
FAQ
Where is the file created? In the program's current working directory unless you give a full path.
Text vs binary mode — which do I use? Text mode ("r", "w") for human-readable files. Binary ("rb", "wb") for raw data like images or structs.
Continue at the hub C Programming, then Strings in C and Pointers in C.
Want to learn this properly? Join the waitlist for our C Programming course — taught in Jalgaon.
Want to learn this properly?
Join the waitlist for C Programming — beginner-friendly, project-first classes in Jalgaon.
Explore C ProgrammingFounder, Infoplanet
Atul Kabra founded Infoplanet in 2001 and has spent over two decades teaching programming — C, C++, Java, databases and more — to students across Maharashtra.
Related guides
Arrays in C
A beginner guide to arrays in C — declaring, initializing and indexing them, looping over elements, multidimensional arrays, and avoiding out-of-bounds errors.
Common C Errors & How to Fix Them
A troubleshooting guide to the most common C errors beginners face — from = vs ==, format mismatches and missing semicolons to segmentation faults — and how to fix each.
Dynamic Memory Allocation in C
A beginner guide to dynamic memory allocation in C — malloc, calloc, realloc and free, allocating at runtime, and preventing memory leaks.
