Normally, when a C program runs, the data it works with is stored temporarily in memory.
But what if we want to save data permanently so we can use it later?
That's where file handling comes in.
What is File Handling?
File handling is the process of creating, opening, reading, writing, and closing files using a C program.
C provides file-handling functions through the stdio.h header file.
The main functions are:
Function | Purpose |
|---|---|
| Opens or creates a file |
| Writes formatted data |
| Reads formatted data |
| Reads a line |
| Writes a string |
| Closes a file |
Opening a File
We use fopen() to open a file.
FILE *file;
file = fopen("data.txt", "w");
Here, FILE * is a pointer used to work with the file.
The second argument specifies the mode.
Common File Modes
Mode | Meaning |
|---|---|
| Open for reading |
| Open for writing; creates or overwrites |
| Open for appending |
| Read and write |
| Read and write; creates or overwrites |
| Read and append |
Writing to a File
We can use fprintf() to write formatted data.
#include <stdio.h>
int main()
{
FILE *file = fopen("data.txt", "w");
if (file == NULL)
return 1;
fprintf(file, "Hello, World!");
fclose(file);
return 0;
}
After running the program, data.txt will contain:
Hello, World!
Reading from a File
We can use fgets() to read text from a file.
char text[100];
FILE *file = fopen("data.txt", "r");
if (file != NULL)
{
fgets(text, sizeof(text), file);
printf("%s", text);
fclose(file);
}
If the file contains:
Hello, World!
the program displays:
Hello, World!
Closing a File
After finishing our work with a file, we should close it using:
fclose(file);
Closing files helps release resources and ensures pending output is properly written.
Simple File Handling Flow
You can remember file handling like this:
Open File
↓
Read / Write
↓
Close File
Always check whether fopen() succeeded before using the returned file pointer.
In Simple Words
File handling allows a C program to store and retrieve data from files.
The basic functions to remember are:
fopen() → Open
fprintf() / fputs() → Write
fscanf() / fgets() → Read
fclose() → Close
File handling is useful when you need data to remain available even after the program finishes, such as storing user information, records, or application data.